Nic Hubbard
Nic Hubbard

Reputation: 42139

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:

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?

Upvotes: 11

Views: 10099

Answers (4)

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

Upvotes: 13

zap
zap

Reputation: 11

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

Upvotes: 0

Ian
Ian

Reputation: 50905

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.

Upvotes: 13

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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.

Upvotes: -2

Related Questions