-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)<<<***; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – 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,776
  • 1
  • 20
  • 36