我想根据嵌套对象的字符串值之一重新排序对象数组。数组必须按此顺序排列。我的尝试有效但似乎是一个臃肿且可能效率低下的解决方案:
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;
}
如何在不创建空位置的情况下重新排序数组?
答案 0 :(得分:2)
// 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));
答案 1 :(得分:1)
您可以定义自定义比较功能,以便与.sort()
一起使用。
这里描述: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
以萨布丽娜的回答为基础:
var aMenu = [
{'name':'A','slug':'salad'},
{'name':'B','slug':'cheeseburger'},
{'name':'C','slug':'fries'}];
var oSlugOrder = {'cheeseburger':0,'salad':1,'fries':2};
aMenu.sort(function(oItemA, oItemB){
return oSlugOrder[oItemA.slug] - oSlugOrder[oItemB.slug]; });