JS Array中reduce實現二維數組轉一維數組和元素次數統計

二維數組轉一維 

// 二維數組轉一維數組
const flattened = [[0,1],[2,3],[4,5]].reduce((a,b) => a.concat(b), [])
console.log(`flattened is ${flattened}`)

數組中元素出現次數統計

// 計算數組中每個元素出現的次數
const names = ['a', 'b', 'a', 'c', 'a', 'c']
const counterNames = names.reduce((allNames, name) => {
  if (name in allNames) {
	allNames[name] += 1
  } else {
	allNames[name] = 1
  }
  return allNames
}, {})
console.log(`counterNames is`)
console.log(counterNames)

 

發佈了259 篇原創文章 · 獲贊 38 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章