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

128
Views
Repeat the array element two times in JavaScript

I was writing a code in JavaScript to just repeat the array element two times. Here is my code.

var arr = [1,2];
for(var i=0;i!=arr.length;i++)
{
  arr.push(arr[i]);
}

for(var i=0;i!=arr.length;i++)
{
  console.log(arr[i]);
}

For example for arr =[1,2 ] output should be [1,2,1,2];

But I am getting error as:FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

arr.length grows while you're pushing new elements into the array. You can store the length in a separate variable:

const arr = [1, 2];
for(let i = 0, length = arr.length; i != length; ++i)
{
  arr.push(arr[i]);
}

for(let i = 0; i != arr.length; ++i)
{
  console.log(arr[i]);
}

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!