我有一个从 API 返回的对象数组。
let arr = [
{name: 'Blur'},
{name: 'The Beatles'},
{name: 'Oasis'},
{name: 'Arctic Monkeys'},
{name: 'Elvis'}
];
我总是希望北极猴子
先于绿洲
出现,并让其他项目保持原样。有时 API 会以正确的顺序返回它们,但在某些情况下,它们会像上面那样以错误的方式返回。
有人可以建议最好的方法吗?
我知道我可以做这样的事情,但我觉得一定有更好的方法。
for(let i = 0; i < arr.length; i++){
if(arr[i].name == 'Arctic Monkeys' && arr[i - 1].name === 'Oasis' ){
let oasisObj = arr[i];
arr[i - 1] = arr[i];
arr[i] = oasisObj;
}
}
或者也许我不应该改变这个数组并创建一个全新的数组?
最佳答案
let arr = [
{name: 'Blur'},
{name: 'The Beatles'},
{name: 'Oasis'},
{name: 'Elvis'},
{name: 'Arctic Monkeys'},
];
// First: look for their indexes
let oasis = -1, monkey = -1; // assuming the indexes are -1
for(let i = 0; i < arr.length && (oasis === -1 || monkey === -1); i++) { // the loop will end when they're both found or the end of the array is reached
if(arr[i].name === "Arctic Monkeys") monkey = i; // if this elemenet is the monkey then assign the current index i to monkey
else if(arr[i].name === "Oasis") oasis = i; // ... same for oasis
}
// Second: if they're not in the right order, change the position of monkey
if(oasis !== -1 && monkey !== -1 && monkey !== oasis - 1) { // if we found them both and if monkey isn't right before oasis, then
monkey = arr.splice(monkey, 1) [0]; // cut monkey out (using splice 1)
arr.splice(oasis, 0, monkey); // insert it right before oasis (using splice 0 monkey)
}
console.log(arr);
关于javascript - 重新排列数组中的对象 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230864/