Sort javascript Array in a pre-defined order
我有一个
这里是我开始的地方,但我不确定如何完成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Items var items = ["Apples","Oranges","Grapes","Peaches","Bananas","Watermelon"]; var itemsOrdered = {}; // Order how I want them for (i in items) { var item = items[i]; if (item == 'Apples') { itemsOrdered['4'] = item; } else if (item == 'Oranges') { itemsOrdered['2'] = item; } else if (item == 'Grapes') { itemsOrdered['1'] = item; } else if (item == 'Peaches') { itemsOrdered['3'] = item; } else if (item == 'Bananas') { itemsOrdered['6'] = item; } else if (item == 'Watermelon') { itemsOrdered['5'] = item; } } |
订单应为:
- 苹果:4个
- 橙子:2个
- 葡萄:1
- 桃子:3个
- 香蕉:6根
- 西瓜:5个
所有这些项可能并不总是在数组中。可能只有苹果和香蕉,但它们仍然需要相同的分类位置。
在创建数组之后,我必须设置这个手动排序顺序,因为我们的系统按这个随机顺序打印它们,然后我们需要正确排序。
最后,我需要将正确排序的水果放回一个数组中。
思想?
尝试:
1 2 3 4 5 6 7 8 9 10 11 | var items = ["Apples","Bananas","Watermelons"]; var itemsOrdered = []; var theOrder = ["Grapes","Oranges","Peaches","Apples","Watermelons","Bananas"]; for (var i = 0; i < theOrder.length; i++) { if (items.indexOf(theOrder[i]) > -1) { itemsOrdered.push(theOrder[i]); } } console.log(itemsOrdered); |
演示:http://jsfiddle.net/jpngs/
订单在
在一个对象中进行排序,如下所示:
1 2 3 4 | var ordering = {}; ordering["Apples"] = 4; ordering["Oranges"] = 2; ... // etc. |
然后使用
编辑:下面是一个实现:
1 2 3 4 5 6 | var ordering = {"Apples":4,"Oranges":2,"Grapes":1, "Peaches":3,"Bananas":6,"Watermelons":5}; var items = ["Apples","Oranges","Grapes", "Peaches","Bananas","Watermelons"]; items.sort(function(a,b) { return ordering[a] - ordering[b]; }) > ["Grapes","Oranges","Peaches","Apples","Watermelons","Bananas"] |
首先将对象转换为数组:
1 2 3 4 | var sortOrder = []; for (i in itemsOrdered) sortOrder[i-1] = itemsOrdered[i]; |
然后像这样使用
1 2 3 | var result = sortOrder.filter(item) { return items.indexOf(item) !== -1; }); |
您的代码简化为:
1 | var itemsOrdered = {1:"Peaches",2:"Oranges",3:"Grapes",4:"Apples",5:"Watermelon",6:"Bananas"}; |
换句话说,这完全没有意义。按照你想要的顺序来定义它们。