我有一个对象数组:
data = [
{
type: "displayName"
base: {}
staged: {}
},
{
type: "bots"
base: {}
staged: {}
},
{
type: "bots"
base: {}
staged: {}
},
{
type: "whiteList"
base: {}
staged: {}
}
]
然后,我有一个要用于订购data
数组的数组:
order = ["bots", "whiteList", "displayName"]
我需要data
根据每个对象进行订购type
我试过了:
private orderChanges = (data: any[], order: any[]) => {
const orderedArray = [];
let len = Object.keys(data).length;
for (; len-- ;) {
const current = data[len];
const index = order.indexOf(current.resourceType);
orderedArray[index] = current;
}
return orderedArray;
}
尽管此方法有效,但只会在orderedArray中返回单个type-> bots对象。
谢谢!
不要重新发明轮子,只要.sort
:
data.sort((a, b) => order.indexOf(b.type) - order.indexOf(a.type));
这需要数组的两个元素(a
和b
),获取它们type
在order
数组内部的索引,然后将这些索引的差返回给排序函数。可能会发生三件事:
1)两者具有相同的顺序:因此它们也具有相同的索引,不同之处在于0
,排序算法将它们保持在相同的位置。
2)A的类型在order数组中较早,索引较低,差为正,因此算法将交换两个元素,因此A优先。
2)B的类型较早,B将移至第一个位置。
对数组中的所有元素重复此操作,直到它们完全排序为止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句