-2

i want to find number of failed values in an array

let courcesStatus = ["passed", "failed", "passed", "passed", "passed", "failed"];

for example want to have 2 here as the number of failed values in this array

  • Please visit [help], take [tour] to see what and [ask]. But first ***>>>[Do some research, search for related topics on SO](https://www.google.com/search?q=javascript+count+elements+in+array+site:stackoverflow.com)<< – mplungjan Jun 18 '21 at 18:41

1 Answers1

0

This is how I would do it, using filter() and length:

let courcesStatus = ["passed", "failed", "passed", "passed", "passed", "failed"];

const howManyFailed = arr => arr.filter(value => value === "failed").length;
console.log(howManyFailed(courcesStatus)); // 2

You could also achieve this with reduce():

let courcesStatus = ["passed", "failed", "passed", "passed", "passed", "failed"];

const howManyFailed = arr => arr.reduce((accu, curr) => accu + (curr === "failed" ? 1 : 0), 0)
console.log(howManyFailed(courcesStatus)); // 2

More information on both of those methods here:

Brandon McConnell
  • 5,256
  • 1
  • 16
  • 27