关于JavaScript中的实用函数封装(数组篇)

关于JavaScript中的实用函数封装

数组

  • 展平一个数组
const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a));
// Or
const flat = arr => arr.reduce((a, b) => Array.isArray(b) ? [...a, ...flat(b)] : [...a, b], []);

// Or
const flat = arr => arr.flat();

// 例子
flat(['cat', ['lion', 'tiger']]);   // ['cat', 'lion', 'tiger']
  • 获取数组中某个值的索引
const indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []);

// Or
const indices = (arr, value) => arr.map((v, i) => v === value ? i : false).filter(Boolean);

// 例子
indices(['h', 'e', 'l', 'l', 'o'], 'l');    // [2, 3]
indices(['h', 'e', 'l', 'l', 'o'], 'w');    // []
  • 获取数组的平均值
const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
  • 获取数组的交集
const getIntersection = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v)));

// 例子
getIntersection([1, 2, 3], [2, 3, 4, 5]);               // [2, 3]
getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]);    // [3]
  • 数组求和
const sum = arr => arr.reduce((a, b) => a + b, 0);
  • 数组去重
const unique = arr => [...new Set(arr)];
  • 获取数组的并集
const union = (...arr) => [...new Set(arr.flat())];

// 例子
union([1, 2], [2, 3], [3]);     // [1, 2, 3]
  • 按键对一组对象进行分组
const groupBy = (arr, key) => arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});

// 例子
groupBy([
    { 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: [
        { branch: 'audi', model: 'q8', year: '2019' },
        { branch: 'audi', model: 'rs7', year: '2020' }
    ],
    bmw: [
        { branch: 'bmw', model: 'x7', year: '2020' }
    ],
    ford: [
        { branch: 'ford', model: 'mustang', year: '2019' },
        { branch: 'ford', model: 'explorer', year: '2020' }
    ],
}
*/
  • 合并两个数组
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];

// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
  • 根据条件对数组进行分区
const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);

// 例子
partition([1, 2, 3, 4, 5], n => n % 2);     // [[2, 4], [1, 3, 5]]
  • 从数组中删除假值
const removeFalsy = arr => arr.filter(Boolean);

// 例子
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); // ['a string', true, 5, 'another string']
  • 打乱数组
const shuffle = arr => arr.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);

// Or
const shuffle = arr => arr.sort(() => .5 - Math.random());

// 例子
shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);   // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]
  • 对数字数组进行排序
const sort = arr => arr.sort((a, b) => a - b);

// 例子
sort([1, 5, 2, 4, 3]);      // [1, 2, 3, 4, 5]
  • 交换矩阵的行和列
const transpose = matrix => matrix[0].map((col, i) => matrix.map(row => row[i]));

// Or
const transpose = matrix => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));

// Or
const transpose = matrix => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);

// 例子
transpose([             // [
    [1, 2, 3],          //      [1, 4, 7],
    [4, 5, 6],          //      [2, 5, 8],
    [7, 8, 9],          //      [3, 6, 9],
]);                     //  ]
扒皮猴社区版权所有,转载请标注出处!
扒皮猴 » 关于JavaScript中的实用函数封装(数组篇)

发表评论