基于另一个数组包含对象数组排序 [英] Sort array containing objects based on another array

查看:122
本文介绍了基于另一个数组包含对象数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/4046967/javascript-sort-an-array-based-on-another-array-of-integers\">JavaScript - 排序基于整数结果的另一个数组的数组
  <一href=\"http://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array\">Javascript - 基于另一个数组排序阵列


如果我有一个这样的数组:

  ['一','四','二']

和另一个数组是这样的:

  [{
  键:一
},{
  键:两节
},{
  键:四
}]

如何将我的第二个数组排序,所以它的属性遵循第一的顺序?在这种情况下,我想:

  [{
  键:一
},{
  键:四
},{
  键:两节
}]


解决方案

下面是我对此采取:

 函数orderArray(array_with_order,array_to_order){
    VAR ordered_array = []
        LEN = array_to_order.length,
        len_copy = LEN,
        指数电流;    对于(; len--;){
        电流= array_to_order [LEN]
        指数= array_with_order.indexOf(current.key);
        ordered_array [指数] =电流;
    }    //改变数组
    Array.prototype.splice.apply(array_to_order,[0,len_copy] .concat(ordered_array));
}

实现:

  VAR array_with_order = ['一','四','二'],    array_to_order = [
        {键:一},
        {键:两节},
        {键:'四'}
    ];orderArray(array_with_order,array_to_order);的console.log(array_to_order); //日志[{键:一},{关键:四},{关键:两节}];

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

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

解决方案

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/

这篇关于基于另一个数组包含对象数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆