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

235
Views
Inserted array shows in reverse JS

I am just starting to learn js and as many (I'm sure) I am facing problems lol. I am trying to copy an array into another array at a designated index location.

I seem to be able to do everything correct but when I log the result, the inserted array shows in reverse and I have no idea why¿?¿?.

Have also tried a .forEach as looping method, but I'm still a bit green to use it right.

This is the code:

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice([]);
  for (let i = 0; i < arr1.length; i++) {
    newArr.splice(n, 0, arr1[i]);
    console.log(newArr)
  }
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

It logs // [ 4, 3, 2, 1, 5, 6 ] instead of the desired out: [ 4, 1, 2, 3, 5, 6 ]

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

0

You are inserting the elements at the same index, so after inserting 1 you insert 2 at the same position, shifting back the 1 and all following elements. Either iterate backwards over arr1 or increment n after each iteration like I have done here.

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice([]);
  for (let i = 0; i < arr1.length; i++) {
    newArr.splice(n, 0, arr1[i]);
    console.log(newArr)
    n++; // add this
  }
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

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!