0

How to remove/unset specific array in javascript? I tried to use splice but i get different result. I think I'm missing something here.

var arr = [12, 3, 150];
var min = 100;
var max = 200
for (var key2 in arr) {
    if (min > arr[key2] || arr[key2] >= max) {
        arr.splice(key2, 1);
    }
}
console.log(arr);

Current code output: [ 3, 150 ]

Expected output: [150]

2
  • 1
    Use filter method and provide predicate in its callback Commented May 20, 2022 at 13:53
  • You should not change the array size inside a loop, unless you handle it. Try to debug this code and see what happens in the second iteration, for example. Commented May 20, 2022 at 14:28

1 Answer 1

3

Filter is way to solve your problem:

var arr = [12, 3, 150];
var min = 100;
var max = 200


console.log(arr.filter(e => e > min && e < max))

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks didn't know that's how to use filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.