I have an array of 3 objects. I have no control over the order of these objects (sent by the backend).
One of these elements has a best property that will be true, but it could be anywhere in the array. I need to get that element and make sure it becomes the middle element of the array. Making a new array and putting it in the middle there is fine. The order of the other objects should be preserved.
However, for the life of me, I can’t figure out how I would solve this problem. Any help or nudge would be appreciated.
Example 1:
[{
title: "HammerDriver",
best: true
},
{
title: "Screwdriver",
best: false
},
{
title: "Hammer",
best: false
}]
should become
[{
title: "Screwdriver",
best: false
},
{
title: "HammerDriver",
best: true
},
{
title: "Hammer",
best: false
}]
Example 2:
[{
title: "Screwdriver",
best: false
},
{
title: "Hammer",
best: false
},
{
title: "HammerDriver",
best: true
}]
should become
[{
title: "Screwdriver",
best: false
},
{
title: "HammerDriver",
best: true
},
{
title: "Hammer",
best: false
}]
Example 3:
[{
title: "Screwdriver",
best: false
},
{
title: "HammerDriver",
best: true
},
{
title: "Hammer",
best: false
}]
should become
[{
title: "Screwdriver",
best: false
},
{
title: "HammerDriver",
best: true
},
{
title: "Hammer",
best: false
}]
>Solution :
Get the index of the best: true element with findIndex(). If it’s not already index 1, splice it out of its current place and splice it back into that index.
const data = [{
title: "HammerDriver",
best: true
},
{
title: "Screwdriver",
best: false
},
{
title: "Hammer",
best: false
}];
const bestIndex = data.findIndex(el => el.best);
if (bestIndex != 1) {
// it's not already in the middle, move it
const best = data[bestIndex];
data.splice(bestIndex, 1); // remove it from current place
data.splice(1, 0, best); // insert it into the middle
}
console.log(data);