-1

I want to remove some element in my array using splice method with if condition in my iteration. I do the following:

var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]

list.forEach(function (item, index) {
    if (item.type == 'service'){
        list.splice(index, 1)
    }
}

//result: list = list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"}]

//expected: list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"}]

I expect the both element with type "service" will be removed, but only the first element is removed.

1
  • Your approach didn't work because when you reached second service, the index: 3 doesn't exist in your array anymore because after your first splice your array length became 3 so last index is 2. Commented Oct 16, 2019 at 7:25

2 Answers 2

2

You can use Array.prototype.filter()

Code:

const list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}];

const resultList = list.filter(item => item.type !== 'service');

console.log(resultList);

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

2 Comments

Should you not vote it as dupe instead?
Thanks for quick response. Problem solved.
0

When using forEach(), If the array is modified during iteration, other elements might be skipped

Why don't use Array.prototype.filter():

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]

list = list.filter( item => item.type != 'service');
console.log(list);

1 Comment

Should you not vote it as dupe instead?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.