簡體   English   中英

如何在JavaScript過濾器函數中訪問鍵值對中的數組

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

我想弄清楚數字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>") 

謝謝,嘗試解決方案https://codepen.io/shihanrehman/pen/JybVJG

您的語法錯誤。 您應該獲取內部數組並對其進行過濾。

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

您需要遍歷數字數組,而不僅僅是外部數組。

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

在您的情況下,減少應該是更好的解決方案。 但是,如果您堅持使用過濾器,請使用以下代碼段:

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

請用這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM