Javascript-按数组重新排列对象数组(值)

阿兹

我有一个对象数组:

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));

这需要数组的两个元素(ab),获取它们typeorder数组内部的索引,然后将这些索引的差返回给排序函数。可能会发生三件事:

1)两者具有相同的顺序:因此它们也具有相同的索引,不同之处在于0,排序算法将它们保持在相同的位置。

2)A的类型在order数组中较早,索引较低,差为正,因此算法将交换两个元素,因此A优先。

2)B的类型较早,B将移至第一个位置。

对数组中的所有元素重复此操作,直到它们完全排序为止。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章