2017-08-05 61 views
2

我想知道在變量「arr」中出現次數/次數2的次數/次數,答案應該是2.如何訪問數組號碼中的數字稱爲'數字'?如何在JavaScript過濾器函數中訪問鍵值對中的數組

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

+0

有兩個數組'arr'和'numbers'所以這你需要檢查數組嗎? – MaxZoom

回答

3

你的語法是錯誤的。你應該採用內部數組並對其進行過濾。

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

+0

我想''
「'是多餘的';-)' –

+0

@MartinAJ可能還有其他代碼。 ;) –

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

0

在你的情況,減少應該是一個更好的解決方案。但是,如果您使用過濾器堅持,然後使用下面的代碼片段:

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

0

請使用

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