如何根据另一个数组的顺序对对象数组进行排序? [英] How do I sort an array of objects based on the ordering of another array?

查看:22
本文介绍了如何根据另一个数组的顺序对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表:

[ { id: 4, name:'alex' }, { id: 3, name:'jess' }, { id: 9, name:'...' }, { id: 1, name:'abc' } ]

我有另一个具有正确顺序"的列表.

I have another list with the right "order".

[ 3, 1, 9, 4]

如何根据键id"将第一个列表与第二个列表的顺序匹配?结果应该是:

How can I match the first list to the ordering of the second list, based on the key "id"? The result should be:

[ { id: 3, name:'jess' }, { id: 1, name:'abc' }, { id: 9, name:'...' }, { id: 4, name:'alex' } ]

推荐答案

我介入了这个问题,并用一个简单的.sort

I stepped in this problem and solved it with a simple .sort

假设您要排序的列表存储在变量 needSort 中,并且带有顺序的列表在变量 order 中,并且两者都在您的同一范围内可以像这样运行 .sort :

Assuming that your list to be sorted is stored in the variable needSort and the list with the order is in the variable order and the both are in the same scope you can run a .sort like this:

needSort.sort(function(a,b){
  return order.indexOf(a.id) - order.indexOf(b.id);
});

它对我有用,希望它有所帮助.

It worked for me, hope it helps.

这篇关于如何根据另一个数组的顺序对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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