gpt4 book ai didi

javascript - 根据精确值重新排序数组

转载 作者:行者123 更新时间:2023-11-28 17:59:36 28 4
gpt4 key购买 nike

我想根据嵌套对象的字符串值之一重新排序对象数组。数组必须按此顺序排列。我的尝试有效,但似乎是一个臃肿且可能效率低下的解决方案:

reorder(order) {
// create array with 4 null positions
var newOrder = [null, null, null, null];

// order can have between 0 - 4 objects
for(var x = 0; x < order.length; x++){

// based on value, assign predefined positions
switch (order[x].slug){
case 'cheeseburger':
newOrder[0] = order[x];
break;
case 'salad':
newOrder[1] = order[x];
break;
case 'fries':
newOrder[2] = order[x];
break;
case 'iceCream':
newOrder[3] = order[x];
break;
}
}
console.log(newOrder);
return newOrder;
}

如何在不创建空位置的情况下重新排序数组?

codepen example

最佳答案

// assume you have the data arr
var arr = [{
slug: 'cheeseburger'
}, {
slug: 'salad'
}, {
slug: 'fries'
}];

function reorder(arr){
// instead of switch, we put the order into an object
var slugOrder = {
cheeseburger: 0,
salad: 1,
fries: 2
};

// with the native sort function you can get expected results
return arr.sort(function(itemA, itemB) {
return slugOrder[itemA] - slugOrder[itemB]
});
}
console.log(reorder(arr));

关于javascript - 根据精确值重新排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43776825/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com