数组常用方法

前言

在开发中,数组的使用场景非常多,不过呢用的多忘的也快,有时候还是会成为CV工程师,所以今天特意总结一下。如果喜欢的话可以点赞支持一下,希望大家看完本文可以有所收获。当然编程之路学无止境,哪里不对还请多多指正。

数组扁平化

将一个对象中各个属性的数组值提取到一个数组集合中

const deps = {
  id1: [1, 2, 3],
  id2: [4, 8, 12],
  id3: [5, 10],
  id4: [88],
};
Object.values(deps).flat(Infinity); // => [1, 2, 3, 4, 8, 12, 5, 10, 88]

flat(depth) 方法中的参数depth,代表展开嵌套数组的深度,默认是1。如果想直接将目标数组变成一维数组,depth的值可以设置为Infinity

生成数字范围内的数组

const arr = [...Array(100).keys()] // => [0, 1, 2, 3, ..., 99]

数组去重

const arr = [1, 2, 2, 4, 5]
const newArr = [...new Set(arr)] // => [0, 1, 2, 4, 5]

数组合并

const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergeArr = [...arr1, ...arr2] // => [1, 2, 3, 4, 5, 6]

数组取交集

const a = [1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7]; 
const intersectionArr = [...new Set(a)].filter(item => b.includes(item)); // => [3, 4, 5]

数组取差集

const a = [1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7]; 
const differenceSet = [...new Set([...a, ...b])].filter(item => !b.includes(item) || !a.includes(item)); // => [1, 2, 6, 7]

删除单个指定值

const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex((x) => x === 2);
const newArr = [...arr.slice(0, index), ...arr.slice(index + 1)]; // => [1, 3, 4, 5]

这里没有使用filter,经个人测试此方法比filter快一丢丢。当然如果你不介意改变原数组可以直接arr.splice(index, 1)这种比创建一个新数组还要快一些

查找单个指定值

const arr = [1, 2, 3, 4, 5];
arr.find(x => x > 1); // => 2

find方法返回数组中满足条件的第一个元素,是元素不是元素下标,如果不存在这样的元素则返回undefined。一旦找到符合条件的项,就不会再继续遍历数组

数组是否包含某数值

const arr = [1, 2, 3, 4, 5];
arr.includes(3) // => true

求数字数组中的最大最小值

const numsArr = [2, 3, 5, 23, 1, 98, 09]
Math.max(...numsArr) // => 98
Math.min(...numsArr) // => 1

你可能感兴趣的:(数组常用方法)