-1

I am trying to perform the sorting array inside the object inside the array

here my First Array Object :

firstObj = [{
    id: "111",
    name: "one",
    type: "user"
},
{
    id: "222",
    name: "two",
    type: "user"
},
{
    id: "333",
    name: "three",
    type: "admin"
},
{
    id: "444",
    name: "four",
    type: "user"
},
{
    id: "555",
    name: "five",
    type: "user"
},
{
    id: "666",
    name: "six",
    type: "admin"
}
]

here my Second Array Object :

secondObj = [
    {
        ids: ['333', '666', '555', '222'],
        name: "handlers"
    }
]

I am successfully sorting First array using below line.

firstObj.sort((p1,p2) => (p1.id > p2.id) ? -1 : 1);

I need a Second array Object ids array Sort with comparing a firstObj id.

I tried many ways But had no luck. Can Anyone Suggest to me How It's possible?

Expected Output:

secondObj = [
    {
        ids: ['222', '333', '555', '666'],
        name: "handlers"
    }
]
  • *Second array Object ids array Sort with comparing a firstObj id.* You mean arrange the ids array based on the sequence from `firstObj`? – Yong Shun Jan 26 '23 at 08:46
  • *"I am successfully sorting First array using below line"* No, that `sort` callback is incorrect. It should be returning `0`, not `1`, when the elements are equal. See MDN's [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) or any example from a reputable source. – T.J. Crowder Jan 26 '23 at 08:49
  • The array is `secondObj[0].ids`. That's what you sort. – T.J. Crowder Jan 26 '23 at 08:50
  • @YongShun Yes You are correct. – Nikunj Chaklasiya Jan 26 '23 at 08:50
  • @NikunjChaklasiya look at the explanation in my answer – Bernard Borg Jan 26 '23 at 08:51
  • @T.J.Crowder I am trying to do => SecondObj ids array Sort with comparing a firstObj id. I mean arrange the ids array based on the sequence from firstObj – Nikunj Chaklasiya Jan 26 '23 at 08:54

1 Answers1

1

let firstObj = [{
    id: "111",
    name: "one",
    type: "user"
},
{
    id: "333",
    name: "two",
    type: "user"
},
{
    id: "222",
    name: "three",
    type: "admin"
},
{
    id: "444",
    name: "four",
    type: "user"
},
{
    id: "555",
    name: "five",
    type: "user"
},
{
    id: "666",
    name: "six",
    type: "admin"
}
];

let secondObj = [
    {
        ids: ['333', '666', '555', '222'],
        name: "handlers"
    }
]

let sortingArr = firstObj.map(x => x.id);

secondObj[0].ids.sort((a, b) => {
   return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});

console.log(secondObj[0].ids);

Note: If your first array is always sorted in ascending order, you can simply sort the second array in ascending order too.

Bernard Borg
  • 1,225
  • 1
  • 5
  • 18