前言
在開發(fā)中,數(shù)組的使用場景非常多,不過呢用的多忘的也快,有時(shí)候還是會成為CV工程師,所以今天特意總結(jié)一下。如果喜歡的話可以點(diǎn)贊??支持一下,希望大家看完本文可以有所收獲。當(dāng)然編程之路學(xué)無止境,哪里不對還請多多指正。
數(shù)組扁平化
將一個對象中各個屬性的數(shù)組值提取到一個數(shù)組集合中
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) 方法中的參數(shù)depth,代表展開嵌套數(shù)組的深度,默認(rèn)是1。如果想直接將目標(biāo)數(shù)組變成一維數(shù)組,depth的值可以設(shè)置為Infinity。
生成數(shù)字范圍內(nèi)的數(shù)組
const arr = [...Array(100).keys()] // => [0, 1, 2, 3, ..., 99]
數(shù)組去重
const arr = [1, 2, 2, 4, 5]
const newArr = [...new Set(arr)] // => [0, 1, 2, 4, 5]
數(shù)組合并
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const mergeArr = [...arr1, ...arr2] // => [1, 2, 3, 4, 5, 6]
數(shù)組取交集
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]
數(shù)組取差集
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,經(jīng)個人測試此方法比filter快一丟丟。當(dāng)然如果你不介意改變原數(shù)組可以直接arr.splice(index, 1)這種比創(chuàng)建一個新數(shù)組還要快一些
查找單個指定值
const arr = [1, 2, 3, 4, 5];
arr.find(x => x > 1); // => 2
find方法返回?cái)?shù)組中滿足條件的第一個元素,是元素不是元素下標(biāo),如果不存在這樣的元素則返回undefined。一旦找到符合條件的項(xiàng),就不會再繼續(xù)遍歷數(shù)組
數(shù)組是否包含某數(shù)值
const arr = [1, 2, 3, 4, 5];
arr.includes(3) // => true
求數(shù)字?jǐn)?shù)組中的最大最小值
const numsArr = [2, 3, 5, 23, 1, 98, 09]
Math.max(...numsArr) // => 98
Math.min(...numsArr) // => 1