订单在theOrder中定义. items包含可用项目. itemsOrdered包含可用的项目,已排序.I have a javascript array that I need to sort in a pre-defined order. It seems random, but they do need to be in a specific order.Here is where I started, but am not sure how to finish:// Itemsvar items = ["Apples", "Oranges", "Grapes", "Peaches", "Bananas", "Watermelon"];var itemsOrdered = {};// Order how I want themfor (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; }}Order should be:Apples: 4Oranges: 2Grapes: 1Peaches: 3Bananas: 6Watermelon: 5All of these items might not always be in the array. It might only be Apples and Bananas, but they still need the same sort positions.I have to set this manual sort order after the array is created because our system prints them out in this random order which we then need to sort correctly.In the end, I need the correctly sorted fruits back in an array.Ideas? 解决方案 Try: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);DEMO: http://jsfiddle.net/JPNGS/The order is defined in theOrder. items contains the available items. itemsOrdered contains the available items, ordered. 这篇关于按预定义顺序对javascript数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-14 05:33