我有一系列專案
const test = [
{
id: '1',
},
{
id: 'a',
},
{
id: '3',
},
{
id: 'b',
},
{
id: '5',
},
{
id: 'c',
},
{
id: '7',
},
];
這些物件總是以相同的順序排列。我希望能夠從一開始就按順序洗掉所有專案,直到id達到特定專案。
我想我可以通過回圈直到找到一個然后將之后的專案推到一個單獨的陣列來做到這一點:
let skippedArray = []
let skipUntilIndex = undefined
test.forEach((item, i) => {
if(item.id === 'b') {
skipUntilIndex = i
}
if(skipUntilIndex && i >= skipUntilIndex) {
skippedArray.push(item)
}
})
// [
// {
// id: 'b',
// },
// {
// id: '5',
// },
// {
// id: 'c',
// },
// {
// id: '7',
// },
// ]
console.log(skippedArray)
但這似乎很骯臟。有沒有更好的方法來實作這一目標?我不介意使用 lodash 或類似的庫。
uj5u.com熱心網友回復:
您可以使用findIndex和slice方法來做到這一點,findIndex您可以在陣列中找到目標項的索引,并且slice可以創建原始陣列的子陣列。
const data = [ { id: '1', }, { id: 'a', }, { id: '3', }, { id: 'b', }, { id: '5', }, { id: 'c', }, { id: '7', }, ];
const getSkippedItems = (id)=> {
const index = data.findIndex(v => v.id == id);
return index > -1 ? data.slice(index) : [];
}
const skippedArr = getSkippedItems('b');
console.log(skippedArr)
uj5u.com熱心網友回復:
您可以使用Array.reduce()過濾掉所有專案,直到達到我們想要的 id。
我們只會在找到所需的 id 后創建輸出陣列,然后將剩余的專案推入其中。
const test = [ { id: '1' }, { id: 'a' }, { id: '3' }, { id: 'b' }, { id: '5' }, { id: 'c' }, { id: '7' } ];
const result = test.reduce((output, item) => {
if (!output && item.id === 'b') output = [];
if (output) output.push(item);
return output;
}, null);
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
您可以對標志進行關閉,如果找到,則通過找到過濾其余部分。
const
removeUntil = (id, found) => o => found ||= o.id === id,
test = [{ id: '1' }, { id: 'a' }, { id: '3' }, { id: 'b' }, { id: '5' }, { id: 'c' }, { id: '7' }],
result = test.filter(removeUntil('b'));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
使用forEach和splice
let k = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}];
let j;
k.forEach((item,idx) => {
if (item.id == 3) {
j = idx;
};
});
k.splice(0, j);
console.log(k); // [{id: 3}, {id: 4}, {id: 5}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/409222.html
標籤:
