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];
}
}
>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));