11

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?

7
  • How do you want them sorted? Can you show us which order? Commented Apr 25, 2013 at 17:39
  • It is there under the "Order how I want them" section. Commented Apr 25, 2013 at 17:39
  • What do you want at position 0? Why are you using an object instead of an array? Commented Apr 25, 2013 at 17:40
  • What is the logic behind such sorting? You can't make an "I-Want-It-Like-That" algorithm. Commented Apr 25, 2013 at 17:41
  • where are you stuck ? Commented Apr 25, 2013 at 17:42

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Not sure how well this scales ... what if theOrder had 100 or 1000 elements and items only had 10 ?
13

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

3 Comments

You are defining an object, not an array.
True. I was thinking more of a hash. A plain object works fine, though. Edited.
You could now use a Map instead of a plain Object for the ordering.
0

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

Comments

-2

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.