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

185
Views
Why can't I remove elements from the array?

This function should remove elements that are less than 1 and more than 4, but it doesn't. The array is still the same.

let arr = [5, 3, 8, 1];

function filterRangeInPlace(arr, a, b) {
    arr.forEach((item, index) => {
        if (a > item && b < item) {
            arr.splice(index, 1);
        };
    });
};

filterRangeInPlace(arr, 1, 4);
console.log(arr);

What's wrong?

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

0

When would an individual item be both less than 1 and more than 4? If you want to remove items that are less than 1 or more than 4 you need to do:

if (a > item || b < item)
about 4 years ago · Juan Pablo Isaza Report

0

you are inverting the arguments when calling the function. you should rather do

filterRangeInPlace(arr, 4, 1)

about 4 years ago · Juan Pablo Isaza Report

0

you are basically keeping items between given range instead removing items go for keeping items this will return same also use filter function it basically iterate through array and just like foreach there are two parameters inside it item and index the only difference is filter keeps value when you return true or ignore if you return false

you can check more about filter here filter

let arr = [5, 3, 8, 1];

function filterRangeInPlace(arr, a, b) {
    return arr.filter(each=>{
       return each > a && each < b
    })
};

arr = filterRangeInPlace(arr, 1, 4);
console.log(arr);

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!