Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
Nic Hubbard Avatar asked Apr 25 '13 17:04

Nic Hubbard


People also ask

How do you sort an array of objects in JavaScript in ascending order?

In JavaScript, arrays come with a built-in function sort(), whose major goal is to sort any element based on alphabetical order. The sort() method sorts the elements of the array in place and returns the sorted array, by default sorting it in ascending order.

How do you sort data in an ordered array?

The elements of an array can be arranged in order by using a static sort() method of the Arrays class. There are sort() methods for arrays of type byte[], char[], double[], float[], int[], and long[] . There is also a method that can sort object references based on the values of the objects.

How do you sort an array in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.


2 Answers

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.

like image 88
Ian Avatar answered Oct 19 '22 02:10

Ian


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"]
like image 40
Reinstate Monica -- notmaynard Avatar answered Oct 19 '22 02:10

Reinstate Monica -- notmaynard