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

251
Views
splice() Method does not remove a specific element from My Array

I Have This Code:

let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];

let newMix = mix.map(function (ele, index) {
    if (typeof ele === "number") {
        mix.splice(index, 1)
    }
})

console.log(mix);

And The Output Is As Follows:

[2, 'l', 'z', 'e', 'r', 'o']

My Question Is: Why Didn't splice() Delete Element 2

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

0

As you splice, the indices are changing. I believe the collection operation you want here is filter rather than map:

let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];

mix = mix.filter(x => typeof x != "number");

console.log(mix);

about 4 years ago · Juan Pablo Isaza Report

0

It's not a good idea to alter the array during a map/forEach, because when you delete an element at index 0, the element at index 1 becomes index 0, and the element at index 2 comes to index 1. So in your case, 1 at index 0 is removed, 2 moves to index 0, and the next iteration starts at index 1 which has 3 currently. So 3 is removed.

See ECMAScript standard specification for

Array.prototype.map to get a better idea.

A better way to do this would be using filter, here's an approach

let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];
let newMix = mix.filter(isNaN);

// OR you can use typeof: let newMix = mix.filter((element) => typeof element !== "number");

console.log(newMix);

about 4 years ago · Juan Pablo Isaza Report

0

Because, when you are splicing the mix array the indexes are being modified as a result.

You can use filter instead

let newMix = mix.filter(function(elem){ 
 return typeof elem !== "number"
})
console.log(newMix)
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!