You want to filter out things from an array. The best thing then is to use the filter method.
var items = [{text: "a", done: false}, {text: "b", done: false}, {text: "c", done: true}, {text: "d", done: true}, {text: "e", done: true}]
console.log(items.filter(o => !o.done))
The problem with your code is you are modifying the array while you are iterating over it, therefore when you remove an element all elements shift, and you skip the next element.
Check the following snippet, and how you never access the (d) element:
var items = [{text: "a", done: false}, {text: "b", done: false}, {text: "c", done: true}, {text: "d", done: true}, {text: "e", done: true}]
var itemsCopy = [{text: "a", done: false}, {text: "b", done: false}, {text: "c", done: true}, {text: "d", done: true}, {text: "e", done: true}]
items.forEach((elem, index) => {
if (itemsCopy[index].text !== items[index].text)
console.log('you want to access', itemsCopy[index].text, 'instead you are accessing', items[index].text)
if(items[index].done) {
items.splice(index, 1);
//elem.remove();
}
})
Every cycle the index increase by 1, so when you remove the c
element, (index 2) then index becomes 3. But since you have deleted the c
, now your array looks like:
[a, b, d, e]
Therefore you are accessing element e
, not d
, because now d
has index 2