二維數組轉一維
// 二維數組轉一維數組
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)