-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.

  • 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. – AvcS Oct 16 '19 at 07:25

2 Answers2

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);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
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);
Mamun
  • 66,969
  • 9
  • 47
  • 59