简体   繁体   English

如何在JavaScript过滤器函数中访问键值对中的数组

[英]How to access an array in key-value pair in a javascript filter function

I want to figure out how many times/count the number 2 appears in variable "arr", the answer should be 2. How do I access the array of numbers in the key called 'numbers'? 我想弄清楚数字2出现在变量“ arr”中的次数/计数,答案应该是2。如何访问称为“数字”的键中的数字数组?

let arr = [{numbers:[2,2,3]}]
//how many times does the number 2 appear in the array above

let newArray = arr.filter(function(e){
  return e.numbers[0] == 2
})

document.write("Occurence of two:" + newArray.length + "<br>") 

thanks, try out solution https://codepen.io/shihanrehman/pen/JybVJG 谢谢,尝试解决方案https://codepen.io/shihanrehman/pen/JybVJG

Your syntax is wrong. 您的语法错误。 You should take the inner array and filter it. 您应该获取内部数组并对其进行过滤。

 let arr = [{numbers:[2,2,3]}] //how many times does the number 2 appear in the array above let newArray = arr[0].numbers.filter(function(e){ return e== 2 }) document.write("Occurence of two:" + newArray.length + "<br>") 

You need to iterate over the array that is numbers, not just the outer array. 您需要遍历数字数组,而不仅仅是外部数组。

 let arr = [{numbers:[2,2,3]}] //how many times does the number 2 appear in the array above let newArray = arr.map((object) => { return object.numbers.filter(element => element === 2); }); document.write("Occurence of two: " + newArray[0].length + "<br>") 

In your case, reduce should be a better solution. 在您的情况下,减少应该是更好的解决方案。 However, if you insist in using filter, then use below code snippet: 但是,如果您坚持使用过滤器,请使用以下代码段:

 let arr = [{numbers:[2,2,3]}]; //how many times does the number 2 appear in the array above let count = arr.reduce((sum, value) => sum + value.numbers.filter(v => v === 2).length, 0); document.write("Occurence of two:" + count + "<br>"); 

Please use this 请用这个

newArray = arr[0].numbers.filter(function(e){
  return e == 2
})

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

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