Sort javascript Array in a pre-defined order

arrays, javascript, sorting

Solution

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.

Problem

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?

Original source