Is there a way to bring the related object to the first index of the array using sort function?
Here is what I tried using sort only
const arr = [{
id: 'a',
name: 'test name 1'
},
{
id: 'b',
name: 'test name 2'
},
{
id: 'c',
name: 'test name 3'
}
];
const testId = 'c';
const sortedArr = arr.sort((a, b) => a.id === testId || b.id === testId ? 1 : -1);
console.log(sortedArr); // logs b, a, c but the expected result is c, a, b
The issue here is because everytime that a OR b are the testId, it will be "bumped". So, if you check only to one value it works.
Here an example :
const arr = [
{
id: 'c'
},
{
id: 'a'
},
{
id: 'b'
}
];
function checkFor(myList, testId) {
console.log('Checking for ' + testId);
const sortedArr = arr.sort((a, b) => b.id === testId ? 1 : -1);
console.log(sortedArr);
}
checkFor(arr, 'c');
checkFor(arr, 'b');