简体   繁体   English

计算数组中值的出现次数

[英]Count the occurrence of value in an array

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 .现在我想要ReactJS中的代码来检查有多少true和多少false

Someone help me.谁来帮帮我。

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

This is not a question about react, but about javascript.这不是关于反应的问题,而是关于 javascript 的问题。

One way to go about that is to write a method that counts all occurences. go 的一种方法是编写一个计算所有出现次数的方法。

values.filter(item => item[1] === true).length

This will filter out only items that are TRUE and return the length of this array.这将仅过滤掉为 TRUE 的项目并返回此数组的长度。 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.过滤假值也可以这样做,或者如果您确定整个过程中只有真值和假值,则可以从数组的长度中减去真值。

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);

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!希望能帮助到你!

I am not really familiar with the values array, but if it keeps its formation you can use this:我不太熟悉 values 数组,但如果它保持其形成,你可以使用它:

let filteredArray = values.filter((val) => val[1] === true).length;

Hope I helped!希望我有所帮助!

How about making use of flat() then filtering it out:如何使用flat()然后将其过滤掉:

 var values = [["Cat", true], ["Dog", false], ["Cow", false], ["Owl", true]] var result = values.flat().filter(k=>k==true).length; console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM