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

How to triplicate specific items in an array for javascript?

Is there any way to only triplicate certain elements in an array? I want to triplicate the "3" in the array only.
For instance:
const deck = [1, 3, 9, 3, 7];
should become [1, 3, 3, 3, 9, 3, 3, 3, 7]

I have tried the method below, deck is the random array:

var i;
  for (let i=0;i<deck.length;i++){
    if (deck[i]==3){
      return deck.flatMap(x=>[x,x,x]);
    }else return deck[i];
  }
}

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

>Solution :

You could write a function that uses flatMap() to map over the array and triplicate the specific values.

const deck = [1, 3, 9, 3, 7];

const triplicate = (number, arr) => {
  return arr.flatMap(x => x === number ? [x, x, x]: x);
}

console.log(triplicate(3, deck));
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