1

I want to remove all element have value isDone === true in array list. But i don't known remove all , I just remove each item one.

This is my code:

  clearCompleted: function (list) {
    for (var i = 0; i < list.length; i++) {
      if (list[i].isDone === true) {
        list.splice(i, 1);
      }
    }
  },

Please help me resolve it.

Trần Hạnh
  • 147
  • 1
  • 10
  • 1
    You can't modify the array you are looping over like that, there are a couple of things you can do to solve this issue. See [this](https://stackoverflow.com/questions/16217333/remove-items-from-array-with-splice-in-for-loop) answer for good solutions. – aaronw May 26 '17 at 01:30

1 Answers1

1

Use while or do..while loop, Array.prototype.indexOf(), Array.prototype.find() to avoid checking original array .length property

let list = [{isDone:true}, {isDone:false}, {isDone:true}];

while (list.find(({isDone}) => isDone)) {
  list.splice(list.indexOf(list.find(({isDone}) => isDone)), 1)
}

console.log(list);
guest271314
  • 1
  • 15
  • 104
  • 177
  • thank you so much. – Trần Hạnh May 26 '17 at 01:38
  • @TrầnHạnh The pattern can be composed using `for` loop `for (;list.find(({isDone}) => isDone);) { list.splice(list.indexOf(list.find(({isDone}) => isDone)), 1) }; ` which uses same amount of characters as `while` loop – guest271314 May 26 '17 at 01:46
  • Thanks for your help . Can you explain `({isDone}) => isDone)` for me? I don't understand it. – Trần Hạnh May 26 '17 at 02:01
  • The syntax is [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and [object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring). Equivalent to `.find(function(object) {return object.isDone} )` – guest271314 May 26 '17 at 02:07
  • Thanks for your support. But I just learn ES5 javascript . :( . This practice just use ES5 – Trần Hạnh May 26 '17 at 02:42
  • @TrầnHạnh Not sure what you mean. The pattern can be composed without using arrow function, object destructuring or `.find()` `for (;list.filter(function(o){return o.isDone}).length;) { list.splice(list.indexOf(list.filter(function(o){return o.isDone})[0]), 1) };` – guest271314 May 26 '17 at 02:46