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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章