Köttur Köttur - 6 months ago 23
Javascript Question

OR (||) operator in angular.forEach not working?

I have the following json array, and need to remove some of them by certain conditions:

var data = [
{data1: "aaa", data2: "bbb", data3: "ccc"}, // First
{data1: "ddd", data2: "eee", data3: "fff"}, // Second
{data1: "ggg", data2: "hhh", data3: "iii"}, // Third
{data1: "jjj", data2: "eee", data3: "lll"} // Fourth
];
angular.forEach(data, (item, i) => {
if (item.data2 == 'eee' || item.data3 == 'iii') {
data.splice(i, 1);
}
});
console.log(data);


In the above case, I need to remove second (data2 has "eee"), third (data3 has "iii"), and fourth (data2 is "eee") object from the data array.
However, the third object is not spliced and remains in data array.

Could I use OR (||) operator in this manner? If not, what is the proper way to remove elements from array using multiple conditions?

I've been scratching my head around for hours with this problem, but perhaps I'm missing something.

Answer

Use filter instead, When using splice you change the array you want to iterate on which is a no no:

var data = [
             {data1: "aaa", data2: "bbb", data3: "ccc"},  // First
             {data1: "ddd", data2: "eee", data3: "fff"},  // Second
             {data1: "ggg", data2: "hhh", data3: "iii"},  // Third
             {data1: "jjj", data2: "eee", data3: "lll"}   // Fourth
           ];
var filtered = data.filter(function (element) {
    return element.data2 !== 'eee' && element.data3 !== 'iii';
});
console.log(filtered);