1.找出数组中最大的元素
const arrayMax = arr => Math.max(...arr); arrayMax([2,3,4]) // 4
2.数组去重
const unique = arr => [...new Set(arr)]; unique([1,2,3,1]) // [1,2,3]
3.统计重复元素出现的次数
let count = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); count([1,2,3,4,4,4],4) // 3
4.拆分数组
const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size)); chunk([1,2,3,4,5,6,7,8],4) // [1,2,3,4] [5,6,7,8]
5.数组元素相加(适用于小数,需引入bigNumber.js)
const sum = arr => arr.reduce((pre, item) => { return new BigNumber(pre).plus(new BigNumber(item)) }, 0) console.log(sum([0.1,0.3]).toString()) // 0.4