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

200
Views
Why is splice working with for loop, but not with map in javascript?

For a 2D array:

var fruits = [["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"]];

why the difference between map and for loop?

var newArrayMap = fruits.map(f => f.splice(1,2));
console.log(newArray);


[["Orange", "Apple"], ["Orange", "Apple"], ["Orange", "Apple"], ["Orange", "Apple"]]
for (var i = fruits.length - 1; i >= 0; i--){
        fruits[i].splice(1,2);
    }
console.log(fruits);

[["Banana", "Pear"], ["Banana", "Pear"], ["Banana", "Pear"], ["Banana", "Pear"]]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Array#splice returns the deleted parts of the array.

In the first loop with map, you take the returned value of splice.

In the second loop with for, you never use the returned value of splice. splice mutates the array and because of that, you get an array without unwanted parts.

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!