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?
0? Why are you using an object instead of an array?