Search code examples
javascriptarraysreactjsobject

How to find the array length depending on the status of an obj flag


I have an array of todos and I am trying to show the num of completed an incompleted todos. I know that I can do array.length and I can find the total num but in this case I am stack.

this.state = {
  text: '',
  notes: [
     {todo: "hello", completed: true},
     {todo: "world", completed: false}
  ]
}

All (notes.length) 2 Completed (?) 0 Incompleted (?) 0


Solution

  • use filter

    let completedCount = this.state.notes.filter(n => n.completed).length;
    let incompleteCount = this.state.notes.length - completedCount;
    

    or use reduce

    let result = this.state.notes.reduce( (acc, curr) => {
       if(curr.completed) acc.complete++;
       else acc.incomplete++;
       return acc;
    }, {complete:0,incomplete:0});
    console.log(result.complete); // 1
    console.log(result.incomplete); // 1