1、將值轉換為數(shù)組
const castArray = value => Array.isArray(value) ? value : [value];
//Examples
castArray(1); // [1]
castArray([1,2,3]); // [1, 2, 3]
2、 檢查數(shù)組是否為空
const isEmpty = arr => !Array.isArray(arr) || arr.length === 0;
// Examples
isEmpty([]); // t rue
isEmpty([1, 2, 3]) // false
3、克隆一個數(shù)組
// `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、比較兩個數(shù)組
// `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、 不管順序比較兩個數(shù)組, 通過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、將對象數(shù)組轉換為單個對象
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、 將字符串數(shù)組轉換為數(shù)字
const toNumbers = arr => arr.map(Number);
const toNumbers = arr => arr.map(x => +x);
// Example
toNumbers(['2', '3', '4']); // [2, 3, 4]
8、按對象數(shù)組的屬性計數(shù)
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、計算數(shù)組中某個值的出現(xiàn)次數(shù)
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、計算數(shù)組元素的出現(xiàn)冊數(shù)
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、創(chuàng)建一個累積和的數(shù)組
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、創(chuàng)建一個范圍內(nèi)的數(shù)字數(shù)組,先給數(shù)組給定長度,然后獲取下標為數(shù)組內(nèi)值,通過下標加最小值
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、 創(chuàng)建笛卡爾積
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、 清空數(shù)組
const empty = arr => arr.length = 0;
arr = [];
15、 從數(shù)組中找到最接近的數(shù)字
// 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、 查找數(shù)組最后一個匹配項的索引
const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index)) => predicate(curr) ? index : prev, -1);
17、計算兩個日期之間的差異天數(shù)
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、 計算兩個日期之間的月數(shù)
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