Array
1. Array shuffling (shuffling function)
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5)
shuffleArray([1,2,3,4,5,6,7,8,9,10,11,12])
2. Generate array
// 方案一
// n为需要生成的范围
const createArray = (n) => new Array(n).fill(0).map((v, i) => i)
// 方案二
const createArray = (n) => Array.from(new Array(n), (v, i) => i)
createArray(100) // 0 - 99数组
3. Array deduplication
// 方案一
const removeDuplicates = (arr) => Array.from(new Set(arr.flat(Infinity)))
// 方案二
const removeDuplicates = (arr) => [...new Set(arr)]
removeDuplicates([1, 4, 3, 4, 5])
4. Maximum index
const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
indexOfMax([1, 3, 9, 7, 5, 10])
5. Minimum value index
const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0)
indexOfMin([2, 5, 3, 4, 1, 0, 9, 11])
6. Intersection of multiple groups
const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9])
7. The closest value
const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev))
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50)
8. Matrix switching
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
transpose(
[ // [
[1, 2, 3], // [1, 4, 7],
[4, 5, 6], // [2, 5, 8],
[7, 8, 9], // [3, 6, 9],
] // ]
);