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

时间:2017-08-05 03:55:18

标签: javascript

我想知道数字2出现在变量" arr"中的次数/次数,答案应该是2.如何访问名为'的密钥中的数字数组?数字&#39 ;?

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

谢谢,试试解决方案 https://codepen.io/shihanrehman/pen/JybVJG

4 个答案:

答案 0 :(得分:2)

你的语法错了。您应该使用内部数组并对其进行过滤。

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

答案 1 :(得分:1)

您需要遍历数字的数组,而不仅仅是外部数组。

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

答案 2 :(得分:0)

在您的情况下,reduce应该是更好的解决方案。但是,如果您坚持使用过滤器,请使用下面的代码段:

&#13;
&#13;
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>");
&#13;
&#13;
&#13;

答案 3 :(得分:0)

请使用此

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