I’ve two array of objects one selected and other general data which we’re displaying
General data for display
const arr = [
{
id: "1",
name: "Skoda - Auto"
},
{
id: "2",
name: "BMW - Auto"
},
{
id: "3",
name: "Mustang"
},
{
id: "2",
name: "Ferrari"
},
{
id: "1",
name: "Ford"
}
];
selectedValues
const selectedArr = [
{
id: "1",
name: "something - 1"
},
{
id: "3",
name: "something - 1"
}
]
I want to sort the general data for display based on this selected array. so basically I want to match the id from selectedArr check if this id is present in general array if yes the shuffle the general array so that selected values are at the top of the array
O/P
const arr = [
{
id: "1",
name: "Skoda - Auto"
},
{
id: "1",
name: "Ford"
},
{
id: "3",
name: "Mustang"
},
{
id: "2",
name: "BMW - Auto"
},
{
id: "2",
name: "Ferrari"
},
];
There are multiple values with same id, I need to unshift those values at the top if it exisits in selected Array. I’m not sure how to achieve such output, hence need some help on this
2
Answers
One not very efficient but easy way to do it is to filter the array twice, creating one array that has the selected elements and one that does not, and then concatenate these two together, like the example below.
This can be achieved by indexing your sorting array into a map that gives an index for a given
id
:then using this in the standard
sort
function (here, I’m taking a copy of the array with[...arr]
becausesort
is in-place and I’m a big fan of avoiding mutation). We give items that are not present in thesortMap
a sufficiently large index that they’ll go to the bottom of the list…Playground Link