简体   繁体   中英

Sort javascript Array in a pre-defined order

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:

// 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;
    }
}

Order should be:

  • Apples: 4
  • Oranges: 2
  • Grapes: 1
  • Peaches: 3
  • Bananas: 6
  • Watermelon: 5

All 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?

Put your ordering in an object, like this:

var ordering = {};
ordering["Apples"] = 4;
ordering["Oranges"] = 2;
... // etc.

Then sort your items array using Array.sort(compareFunction(a, b)) , passing it a sorting function to check your objects against ordering (left as an exercise). Check out https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort to see how compareFunction() is used.

Edit: Here's an implementation:

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"]

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.

Your code simplifies to:

var itemsOrdered = {1:"Peaches",2:"Oranges",3:"Grapes",4:"Apples",5:"Watermelon",6:"Bananas"};

In other words, it's completely pointless. Just define them in the order you want them.

First convert your object to an Array:

var sortOrder = [];

for (i in itemsOrdered)
    sortOrder[i-1] = itemsOrdered[i];

Then use .filter() like this:

var result = sortOrder.filter(item) {
    return items.indexOf(item) !== -1;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM