排序包含基于另一个数组的对象的数组

时间:2012-11-22 18:30:22

标签: javascript arrays sorting

  

可能重复:
  JavaScript - Sort an array based on another array of integers
  Javascript - sort array based on another array

如果我有这样的数组:

['one','four','two']

另一个像这样的数组:

[{
  key: 'one'
},{
  key: 'two'
},{
  key: 'four'
}]

我如何对第二个数组进行排序,使其key属性遵循第一个数组的顺序?在这种情况下,我想:

[{
  key: 'one'
},{
  key: 'four'
},{
  key: 'two'
}]

2 个答案:

答案 0 :(得分:6)

我们可以使用sort()函数通过传递一个自定义函数来执行此操作,该函数执行比较。此函数必须返回3个可能的值,给定ab进行比较:

return -1如果a的编入索引低于b

如果return 0被视为等于a

,则

b

return 1如果a的索引编号大于b

考虑到这一点,我们可以定义一个如下函数:

function sortFunction(a,b){
    var indexA = arr.indexOf(a['key']);
    var indexB = arr.indexOf(b['key']);
    if(indexA < indexB) {
        return -1;
    }else if(indexA > indexB) {
        return 1;
    }else{
        return 0;       
    }
}

此函数将接收您在数组中定义的对象,并查找该值在arr数组中的位置,该数组是您要比较的数组。然后它会比较索引,并根据需要返回值。

我们通过将函数传递到sort()函数来使用此函数:

testArray.sort(sortFunction)

其中testArray是您要排序的数组。

你可以看看这里,我做了这个例子,你可以在调用sort函数之前和之后看到数组中的第二个对象被“警告”。 http://jsfiddle.net/Sqys7/

答案 1 :(得分:3)

这是我的看法:

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'}];

通常的小提琴:http://jsfiddle.net/joplomacedo/haqFH/