Sort array containing objects based on another array
arrays, javascript, sorting
Solution
Here's my take on it:
function orderArray(array_with_order, array_to_order) {
var ordered_array = [],
len = array_to_order.length,
len_copy = len,
index, current;
for (; len--;) {
current = array_to_order[len];
index = array_with_order.indexOf(current.key);
ordered_array[index] = current;
}
//change the array
Array.prototype.splice.apply(array_to_order, [0, len_copy].concat(ordered_array));
}
Sample implementation:
var array_with_order = ['one', 'four', 'two'],
array_to_order = [
{key: 'one'},
{key: 'two'},
{key: 'four'}
];
orderArray(array_with_order, array_to_order);
console.log(array_to_order); //logs [{key: 'one'}, {key: 'four'}, {key: 'two'}];
The usual fiddle: http://jsfiddle.net/joplomacedo/haqFH/
Problem
Possible Duplicate: JavaScript - Sort an array based on another array of integers Javascript - sort array based on another array If I have an array like this: ``` ['one','four','two'] ``` And another array like this: ``` [{ key: 'one' },{ key: 'two' },{ key: 'four' }] ``` How would I sort the second array so it’s `key` property follows the order of the first? In this case, I want: ``` [{ key: 'one' },{ key: 'four' },{ key: 'two' }] ```