Reputation: 185
I have an array as below:
values = [["Cat", true], ["Dog", false], ["Cow", false], ["Owl", true]]
Now I want a code in ReactJS
to check how many true
are there and how many false
.
Someone help me.
Upvotes: 0
Views: 96
Reputation: 29
This is not a question about react, but about javascript.
One way to go about that is to write a method that counts all occurences.
values.filter(item => item[1] === true).length
This will filter out only items that are TRUE and return the length of this array. Same can be done for filtering false values, or you can subtract true values from the length of the array if you're sure you only have true and false values throughout.
Upvotes: 1
Reputation: 725
Be careful with Truthy & Falsy
let values = [
["Cat", true],
["Dog", false],
["Cow", 1],
["Owl", 0],
["donkey", 0]
]
let truthy = 0;
let nonTruthy = 0;
let trueCount = 0;
let falseCount = 0;
values.forEach(ele => {
if (ele[1] === true) trueCount++;
if (ele[1] === false) falseCount++;
})
values.forEach(ele => {
ele[1] ? truthy++ : nonTruthy++
})
console.log(trueCount, falseCount) // 1 1
console.log(truthy, nonTruthy) // 2 3
Upvotes: 2
Reputation: 5308
How about making use of flat()
then filtering it out:
var values = [["Cat", true], ["Dog", false], ["Cow", false], ["Owl", true]]
var result = values.flat().filter(k=>k==true).length;
console.log(result);
Upvotes: 0
Reputation: 3
I am not really familiar with the values array, but if it keeps its formation you can use this:
let filteredArray = values.filter((val) => val[1] === true).length;
Hope I helped!
Upvotes: 0
Reputation: 604
The simplest way to achive it is to use filter
const values = [["Cat", true], ["Dog", false], ["Cow", false], ["Owl", true]];
const trueVals = values.filter(item => item[1]).length;
const falseVals = values - trueVals;
hope it helps!
Upvotes: 0
Reputation: 5390
Working example:
const values = [["Cat", true], ["Dog", false], ["Cow", false], ["Owl", true]];
let counter = 0;
values.map((item) => {
if (item[1]) {
counter++;
}
});
console.log(counter);
Upvotes: 0