Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: How to find a specific element in a 3-element array and make sure it is always in the middle of that array?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading