Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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];
  }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

Using Array#flatMap:

const triplicate = (arr = [], number) => 
  arr.flatMap(n => n === number ? [n, n, n] : n);

console.log( triplicate([1, 3, 9, 3, 7], 3) );

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!