1、将值转换为数组
const castArray = value => Array.isArray(value) ? value : [value];
//Examples
castArray(1); // [1]
castArray([1,2,3]); // [1, 2, 3]
2、 检查数组是否为空
const isEmpty = arr => !Array.isArray(arr) || arr.length === 0;
// Examples
isEmpty([]); // t rue
isEmpty([1, 2, 3]) // false
3、克隆一个数组
// `arr` is an array
const clone = arr => arr.slice(0);
// Or 使用扩展运算符
const clone = arr => [...arr];
const clone = arr => Array.from(arr);
const clone = arr => arr.map(x => x);
const clone = arr => JSON.parse(JSON.stringify(arr));
const clone = arr => arr.concat([]);
4、比较两个数组
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
//Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
5、 不管顺序比较两个数组, 通过sort方法进行排序后进行比较
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // false
isEqual([1, 2, 3], [1, '2', 3]); // false
6、将对象数组转换为单个对象
const toObject = (arr, key) => arr.reduce((a, b) => ({...a, [b[key]] : b }), {});
toObject(
[
[{ id: '1', name: 'Alpha',gender:'Male' }],
[{ id: '2', name: 'Bravo',gender:'Male' }],
[{ id: '3', name: 'Charlie',gender:'Female' }]
],
' id '
)
7、 将字符串数组转换为数字
const toNumbers = arr => arr.map(Number);
const toNumbers = arr => arr.map(x => +x);
// Example
toNumbers(['2', '3', '4']); // [2, 3, 4]
8、按对象数组的属性计数
const countBy = (arr, prop) => arr.reduce((prev, curr) => (prev[curr[prop]] = ++ prev[curr[prop]] || 1, prev), {});
// Example
countBy([
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' }
], 'branch')
// { 'audi': 2, 'ford': 2, 'bmw': 1 }
9、计算数组中某个值的出现次数
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a+1 : a), 0);
const countOccurrences = (arr,val) => arr.filter(item => item === val).length;
// Example
countOccurrences ([2, 1, 3, 3, 2, 3], 2); // 2
countOccurrences (['a', 'b', 'a', 'c', 'a', 'b'], 'a'); //3
10、计算数组元素的出现册数
const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[cuyrr] || 1, prev), {});
// Examples
countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 }
11、创建一个累积和的数组
const accumulate = arr => arr.map((sum => value => sum += value), (0));
const accumulate = arr => arr.reduce((a, b, i) => i===0 ? [b] : [...a, b + a[i-1]], []);
const accumulate = arr => arr.reduce((a, b, i) => i === 0 ? [b] : [...a, b + a[i-1]], 0);
//Example
accumulate([1, 2, 3, 4,]); // [1, 2, 6, 10]
12、创建一个范围内的数字数组,先给数组给定长度,然后获取下标为数组内值,通过下标加最小值
const range = (min, max) => [...Array(max - min +1).keys()].map(i => i+min);
const range = (min, max) => Array(max - min + 1).fill(0).map((_, i) => min + i);
const range = (min, max) => Array.from({length: max - min + 1}, (_, i) => min + i);
// Example
range(5, 10);
13、 创建笛卡尔积
const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]);
// Example
cartesian ([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ]
14、 清空数组
const empty = arr => arr.length = 0;
arr = [];
15、 从数组中找到最接近的数字
// Find the number from `arr` which is closest to `n`
const closest = (arr, n) => arr.reduce => arr.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev);
const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - nm))[0];
// Examle
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
16、 查找数组最后一个匹配项的索引
const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index)) => predicate(curr) ? index : prev, -1);
17、计算两个日期之间的差异天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
// Example
diffDays(new Date('2014-12-19'), new Date('2020-01-01')); //1839
18、 计算两个日期之间的月数
const monthDiff = (startDate, endDate) => Math.max(0,
(endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
// Example
monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12