Javascript按数组排序对象数组

时间:2022-07-08 16:00:48

I have an array of objects structured like so (this is just example) and an array of id:

我有一个像这样构造的对象数组(这只是示例)和一个id数组:

var array_objects=[
        {id:'a',value:1},
        {id:'b',value:2},
        {id:'c',value:2},
        {id:'d',value:3}
        ];

var array =['b','c','a','d'];

I wish to reorder array_objects the same way array is ordered. The order in the array can change each time. How to do this?

我希望以与排序数组相同的方式重新排序array_objects。数组中的顺序每次都可以更改。这该怎么做?

3 个解决方案

#1


A simple solution:

简单的解决方案:

array_objects.sort(function(a,b){
  return array.indexOf(a.id)-array.indexOf(b.id)
})

If you have a very big array and you want something really fast, here's a variant not calling indexOf:

如果你有一个非常大的数组并且你想要一些非常快的东西,这里有一个不调用indexOf的变体:

var m = array.reduce(function(r,k,i){ return r[k]=i,r },{});
array_objects.sort(function(a,b){ return m[a.id]-m[b.id] });

#2


Easiest to generate a new array.

最容易生成一个新数组。

var arr2 = [], i;

for (i = 0; i < array.length; ++i)
    arr2[array.indexOf(array_objects[i].id)] = array_objects[i];

If it's important to use the same reference, you can do some magic with splice

如果使用相同的参考是很重要的,你可以用拼接做一些魔术

var i;
for (i = 0; i < array.length; ++i)
    array_objects[array.indexOf(array_objects[i].id) + array.length] = array_objects[i];
array_objects.splice(0, array.length);

#3


I think this quite simple, try this:

我觉得这很简单,试试这个:

array_objects.sort(function(a,b){
  return (a.id) > (b.id)
});

#1


A simple solution:

简单的解决方案:

array_objects.sort(function(a,b){
  return array.indexOf(a.id)-array.indexOf(b.id)
})

If you have a very big array and you want something really fast, here's a variant not calling indexOf:

如果你有一个非常大的数组并且你想要一些非常快的东西,这里有一个不调用indexOf的变体:

var m = array.reduce(function(r,k,i){ return r[k]=i,r },{});
array_objects.sort(function(a,b){ return m[a.id]-m[b.id] });

#2


Easiest to generate a new array.

最容易生成一个新数组。

var arr2 = [], i;

for (i = 0; i < array.length; ++i)
    arr2[array.indexOf(array_objects[i].id)] = array_objects[i];

If it's important to use the same reference, you can do some magic with splice

如果使用相同的参考是很重要的,你可以用拼接做一些魔术

var i;
for (i = 0; i < array.length; ++i)
    array_objects[array.indexOf(array_objects[i].id) + array.length] = array_objects[i];
array_objects.splice(0, array.length);

#3


I think this quite simple, try this:

我觉得这很简单,试试这个:

array_objects.sort(function(a,b){
  return (a.id) > (b.id)
});