基于另一个数组对包含对象的数组进行排序
问题描述:
可能的重复:
JavaScript - 基于另一个整数数组对数组进行排序
Javascript - 基于另一个数组对数组进行排序
如果我有一个这样的数组:
If I have an array like this:
['one','four','two']
还有一个像这样的数组:
And another array like this:
[{
key: 'one'
},{
key: 'two'
},{
key: 'four'
}]
如何对第二个数组进行排序,使其 key
属性遵循第一个数组的顺序?在这种情况下,我想要:
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'
}]
答
这是我的看法:
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));
}
示例实现:
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'}];