如何通过另一个数组ID(lodash / javascript)来排序数组

时间:2018-02-09 08:21:50

标签: javascript lodash

我希望我的第二个数组按属性id排序,就像在第一个数组中一样。

这是我的数组

第一个数组

data : 
  items:
    0: {id: 14, attributes: Array(1)}
    1: {id: 8, attributes: Array(1)}
    2: {id: 4, attributes: Array(1)}
    3: {id: 1, attributes: Array(2)}
    4: {id: 2045, attributes: Array(2)}

第二个数组

data : 
  items:
    0: {id: 1, name: "test Product 1"}
    1: {id: 4, name: "test Product 1"}
    2: {id: 8, name: "test Product 1"}
    3: {id: 14, name: "test Product 1"}
    4: {id: 2045, name: "test Product 1"}

我试过这样:

Javascript - sort array based on another array

但我似乎无法让它发挥作用。 我知道这被问了很多,但我无法理解。

2 个答案:

答案 0 :(得分:2)

您可以按第一个数组的索引排序。

        Linker linker = new Linker();
        linker.InitializeLinkMethods();

        ICat cat = new Cat() {Name = "The CAT"};
        IDog dog = new Dog() {Name = "the DOG"};
        IMouse mouse = new Mouse() {Name = "The MOUSE"};


        linker.Link<ICat, IMouse>(cat, mouse);
        linker.Link(dog, cat);

&#13;
&#13;
items2.sort((a, b) =>
    items1.findIndex(({ id }) => a.id === id) -
    items1.findIndex(({ id }) => b.id === id));
&#13;
var items1 = [{ id: 14, attributes: [1] }, { id: 8, attributes: [1] }, { id: 4, attributes: [1] }, { id: 1, attributes: [1] }, { id: 2045, attributes: [1, 2] }],
    items2 = [{ id: 1, name: "test Product 1" }, { id: 4, name: "test Product 1" }, { id: 8, name: "test Product 1" }, { id: 14, name: "test Product 1" }, { id: 2045, name: "test Product 1" }];

items2.sort((a, b) => items1.findIndex(({ id }) => a.id === id) - items1.findIndex(({ id }) => b.id === id));

console.log(items2);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

lodash

sorted = _.sortBy(items1, x => _.findIndex(items2, y => x.id === y.id))

如果您的数组相当长,那么首先构建索引可能会更有效率,然后按此排序:

index = _.fromPairs(_.map(items2, (x, i) => [x.id, i]));
sorted = _.sortBy(items1, x => index[x.id])