Skip to content
Advertisement

Sort array of objects based on another array of objects key

I have 2 arrays of objects

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. 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. In array1 the first B is at index 0 and the second B is at index 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);
      });

Advertisement

Answer

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.

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)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement