数组工具函数

判断是否全部相等

使用Array.prototype.every()以检查所有元素都与第一个相同, every()是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。

const allEqual = arr => arr.every(val => val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true

求数组中的平均数

使用Array.prototype.reduce()将数组中的元素进行相加,再除以数组长度。

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2

求数组中的平均数(指定key)

使用Array.prototype.reduce()将数组中的元素进行相加,再除以数组长度,fn可为key或者方法。

const averageBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
  arr.length;
  
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5

计算数组某个值出现次数

使用Array.prototype.reduce()判断指定元素出现次数,如果等于结果+1。

const countOccurrences = (arr, val) => 
    arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

递归扁平化数组(flat)

这个方法可以用于不支持flat函数的浏览器上,使用concat连接数组,再使用map判断元素对于的是否为数组,是则继续递归自身

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

指定深度扁平化数组

这个方法可以用于不支持flat函数的浏览器上,可以指定处理层级,使用concat连接数组,再使用map判断元素对于的是否为数组,是则继续递归自身


const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]

查找数组某个值的索引

此代码段可用于获取数组中某个值的所有索引,如果此值中未包含该值,则返回一个空数组。

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []

两数组的交集

const intersection = (a, b) => {
   const s = new Set(b);
   return a.filter(x => s.has(x));
 };
 
 intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

根据指定key生成树结构

使用Array.prototype.filter()返回子级,map生成树型

const nest = (items, id = null, link = 'parent_id') =>
  items
    .filter(item => item[link] === id)
    .map(item => ({ ...item, children: nest(items, item.id) }));


const comments = [
  { id: 1, parent_id: null },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
];
const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]