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
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
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: