简体   繁体   English

根据另一个对象数组键对对象数组进行排序

[英]Sort array of objects based on another array of objects key

I have 2 arrays of objects我有 2 个 arrays 对象

array1 = [
    {
        "name": "B",
        "order": 1
    },
    {
        "name": "C",
        "order": 2
    },
    {
        "name": "D",
        "order": 3
    },
    {
        "name": "B",
        "order": 4
    },
    {
        "name": "A",
        "order": 5
    }
]

array2 = [
    {
        "name": "B",
        "order": 1,
        "id": 3638
    },
    {
        "name": "B",
        "order": 1,
        "id": 3661
    },
    {
        "name": "C",
        "order": 2,
        "id": 3658
    },
    {
        "name": "D",
        "order": 3,
        "id": 3659
    },
    {
        "name": "A",
        "order": 5,
        "id": 3636
    }
]

I need to sort array2 to match the same order of array1 based on the property name.我需要根据属性名称对 array2 进行排序以匹配 array1 的相同顺序。 In array2 there are 2 names properties equal with value B. These name B are together but i need the array to be in the exact order of array1.在array2 中有2 个与值B 相等的名称属性。这些名称B 在一起,但我需要数组与array1 的顺序完全相同。 In array1 the first B is at index 0 and the second B is at index 3.在 array1 中,第一个 B 位于索引 0 处,第二个 B 位于索引 3 处。

I made this attempts without luck.我没有运气就做了这个尝试。

array2.sort((a, b) => array1.indexOf(a.name) - array1.indexOf(b.name));

let sorted = array2.sort((a, b) => {
        return array1.findIndex(p => p.name=== a.name) - array1.findIndex(p => p.name=== b.name);
      });

You can try this, it finds the first elem in array2 matching the name, in order, from the array1 .. removes it from array2 and then adds it to the sortedArray2 .你可以试试这个,它会在array2中找到与名称匹配的第一个元素,按顺序从array1 .. 将其从array2中删除,然后将其添加到sortedArray2

 const array1 = [ { "name": "B", "order": 1 }, { "name": "C", "order": 2 }, { "name": "D", "order": 3 }, { "name": "B", "order": 4 }, { "name": "A", "order": 5 } ] const array2 = [ { "name": "B", "order": 1, "id": 3638 }, { "name": "B", "order": 1, "id": 3661 }, { "name": "C", "order": 2, "id": 3658 }, { "name": "D", "order": 3, "id": 3659 }, { "name": "A", "order": 5, "id": 3636 } ] const sortedArray2 = [] for(const item of array1) { sortedArray2.push( array2.splice( array2.findIndex(elem => elem.name === item.name), 1 ) ) } console.log(sortedArray2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM