数组
One-Liner
检查变量是否是数组
const isArray = Array.isArray(arr);
const isArray = arr instanceof Array;
数字数组的和
const sum = arr => arr.reduce((a, b) => a + b);
从数组中删除Falsy值
const removeFalsyValues = arr => arr.filter(x => x);
// or
const removeFalsyValues = arr => arr.filter(Boolean);
数字数组的平均值
const average = arr => arr.reduce((a, b) => a + b) / arr.length;
合并并删除重复项
const merge = (arr1, arr2) => [...new Set(arr1.concat(arr2))];
// or
const merge = (arr1, arr2) => [...new Set([...arr1, ...arr2])];
合并两个数组
const merge = (arr1, arr2) => [].concat(arr1, arr2);
// or
const merge = (arr1, arr2) => [...arr1, ...arr2];
打乱数组
const shuffle = arr => arr.slice().sort(() => Math.random() - 0.5);
获取数组的最后一个元素
const lastElement = arr => arr[arr.length - 1];
// or
const lastElement = arr => arr.slice(-1)[0];
// or
const lastElement = arr => arr.slice().pop();
查找数组中的唯一值
const findUniqueValues = arr =>
arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
克隆数组
const clone = arr => arr.slice();
// or
const clone = arr => [...arr];