根据另一个数组按顺序对数组进行排序 [英] Sort array by order according to another array

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

问题描述

我有一个从数据库中返回的对象,如下所示:[{id:1},{id:2},{id:3}].我还有另一个数组,它指定了第一个数组的排序顺序,例如:[2,3,1].

I have an object that is being returned from a database like this: [{id:1},{id:2},{id:3}]. I have another array which specified the order the first array should be sorted in, like this: [2,3,1].

我正在寻找可以接受这两个数组并返回[{id:2},{id:3},{id:1}]的方法或算法.理想情况下,它应该是高效的,而不是n平方.

I'm looking for a method or algorithm that can take in these two arrays and return [{id:2},{id:3},{id:1}]. Ideally it should be sort of efficient and not n squared.

推荐答案

如果要使用线性时间,请首先从第一个数组构建一个哈希表,然后通过循环第二个数组按顺序选择项:

If you want linear time, first build a hashtable from the first array and then pick items in order by looping the second one:

data = [{id:5},{id:2},{id:9}]
order = [9,5,2]

hash = {}
data.forEach(function(x) { hash[x.id] = x })

sorted = order.map(function(x) { return hash[x] })

document.write(JSON.stringify(sorted))

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

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