天天看點

18個項目必備的JavaScript代碼片段——數組篇

大家好,我是若川​。最近組織了源碼共讀活動​,感興趣的可以加我​ 參與,目前近3000人參與,0-5年工作經驗的都可以參與學習。

1.​

​chunk​

​轉換二維數組

将數組(array)拆分成多個數組,并将這些拆分的多個數組組成一個新數組。

function chunk(array, count = 1) {
    let pages = []
    array.forEach((item, index) => {
        const page = Math.floor(index / count)
        if (!pages[page]) pages[page] = []
        pages[page].push(item)
    })
    return pages
}      

小栗子

chunk([1, 2, 3, 4, 5, 6, 7], 2)
=> [[1, 2], [3, 4], [5, 6], [7]]

chunk(['a', 'b', 'c', 'd'], 3)
=> [['a', 'b', 'c'], ['d']]      

2.​

​cloneArray​

​克隆數組

淺拷貝一份數組副本。

// ES6 ...
const cloneArray = arr => [...arr]

// ES6 Array.from
const cloneArray = arr => Array.from(arr)

// concat()
const cloneArray = arr => [].concat(arr)

// map()
const cloneArray = arr => arr.map(x => x)

cloneArray([1, 24]) // [1, 24]      

小栗子

cloneArray([1, 24])
// => [1, 24]      

3.​

​compact​

​去除數組中的無效值

建立一個新數組,包含原數組中所有的非假值元素。例如​

​false​

​​, ​

​null​

​​,​

​0​

​​, ​

​""​

​​, ​

​undefined​

​​, 和 ​

​NaN​

​ 都是被認為是“假值”。

const compact = arr => arr.filter(Boolean)      

小栗子

min([0, 1, false, 2, '', 3])
// => [1, 2, 3]      

4.​

​difference​

​ 數組差集

建立一個具有唯一​

​array​

​值的數組,每個值不包含在其他給定的數組中。

假設有 ​

​A​

​​ 和 ​

​B​

​​ 兩個數組,傳回 ​

​A​

​​ 數組中的集合不包含 ​

​B​

​ 數組中的集合。

const difference = (a, b) => {
  const s = new Set(b)
  let arr = a.filter(x => !s.has(x))
  return arr
}      

小栗子

difference([1, 2, 6, 7], [1, 2, 9, 5])
// => [ 6, 7 ]      

5.​

​intersection​

​數組集合

建立一個共有的​

​array​

​值的數組,每個值包含在其他給定的數組中。

const intersection = (a, b) => {
    const s = new Set(b)
    return a.filter(x => s.has(x))
}
// ES6 includes
const intersection = (arr, values) => arr.filter(v => values.includes(v))      

小栗子

intersection([1, 2, 6, 7], [1, 2, 9, 5])
// => [ 1, 2 ]      

6.​

​flatten​

​扁平化數組

将多層嵌套數組(array)拆分成一個數組。

// 扁平化  Map 方法
const flatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? flatten(v) : v)))

// 扁平化  reduce 方法
const flatten = arr => arr.reduce((a, c) => a.concat(Array.isArray(c) ? flatten(c) : c), [])      

小栗子

flatten([1, [2], [3], [4, 5]])

=> [1, 2, 3, 4, 5]      

7.​

​flattenDeep​

​指定層級扁平化數組

将多層嵌套數組(array)拆分成指定層級數組。

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

// ES6方法 `flat(depth)`
[1, [2, [3, [4]], 5]].flat(1)
// => [1, 2, [3, [4]], 5]      

小栗子

flattenDeep([1, [2, [3, [4]], 5]], 1)
// => [1, 2, [3, [4]], 5]      

8.​

​isArrayEqual​

​檢查兩個數組各項相等

比較兩個數組内的各項值是否相等,傳回一個​

​Boolean​

​值。

const isArrayEqual = (a, b, has = true) => {
  if (a.length !== b.length) return (has = false)
  const s = new Set(b)
  if (a.find(x => !s.has(x))) return (has = false)
  return has
}      

小栗子

isArrayEqual([6, 5, 2, 4, 1, 3], [1, 2, 3, 4, 5, 6])
// => true

isArrayEqual([6, 5, 2, 7, 1, 3], [1, 2, 3, 4, 5, 6])
// => false      

9.​

​max​

​數組中最大值

過濾原數組中所有的非假值元素,傳回數組中的最大值。

const max = arr => Math.max(...arr.filter(v => Boolean(v) || v === 0))      

小栗子

max([0, -1, -2, -3, false])
// => 0      

10.​

​min​

​數組中最小值

過濾原數組中所有的非假值元素,傳回數組中的最小值

const min = arr => Math.min(...arr.filter(v => Boolean(v) || v === 0))      

小栗子

min([0, -1, -2, -3, false])
// => -3      

11.​

​shuffle​

​打亂數組

建立一個打亂的數組,使用​

​Fisher-Yates​

​算法打亂數組的元素。

const shuffle = ([...arr]) => {
    let m = arr.length
    while (m) {
        const i = Math.floor(Math.random() * m--);
        [arr[m], arr[i]] = [arr[i], arr[m]]
    }
    return arr
}      

小栗子

shuffle([2, 3, 1])
// => [3, 1, 2]      

12.​

​sortAsc​

​數組升序

傳回升序後的新數組

sort()方法會改變原數組,預設按 unicode 碼順序排列
// 通過ES6 ...展開運算符淺拷貝一份新數組
const sortAsc = arr => [...arr].sort((a, b) => a - b)      

小栗子

sortAsc([3, 2, 3, 4, 1])
// => [ 1, 2, 3, 3, 4 ]      

13.​

​sortDesc​

​數組降序

傳回降序後的新數組。

const sortDesc = arr => [...arr].sort((a, b) => b - a)      

小栗子

sortDesc([3, 2, 3, 4, 1])
// => [ 1, 2, 3, 3, 4 ]      

14.​

​take​

​截取數組開始指定的元素

從 array 數組的最開始一個元素開始提取 n 個元素。

const take = (arr, n = 1) => arr.slice(0, n)      

小栗子

take([2, 3, 1], 2)
// => [2, 3]      

15.​

​takeLast​

​截取數組末尾元素

從 array 數組的最後一個元素開始提取 n 個元素

const takeLast = (arr, n = 1) => arr.slice(0, -n)      

小栗子

take([2, 3, 1], 2)
// => [3, 1]      

16.​

​treeData​

​生成樹結構資料

該函數傳入一個數組, 每項​

​id​

​​對應其父級資料​

​parent_id​

​,傳回一個樹結構數組

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

參數

  • ​array​

    ​ 要生成樹結構的數組
  • ​id​

    ​ 自定義屬性名
  • ​parent_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 },
]

treeData(comments)

// => [ { id: 1, parent_id: null, children: [ [Object], [Object] ] } ]      

17.​

​unique​

​數組去重

建立一個去重後的 array 數組副本。

const unique = (...arr) => [...new Set(arr)]

// const unique = (...arr) => Array.from(new Set(arr))      

小栗子

unique([1, 2, 2, 3, 4, 4, 5])
// => [ 1, 2, 3, 4, 5 ]      

18.​

​uniqueBy​

​數組對象去重

建立一個去重後的 array 數組對象副本。

const uniqueBy = (arr, key) => {
    return arr.reduce((acc, cur) => {
        const ids = acc.map(item => item[key])
        return ids.includes(cur[key]) ? acc : [...acc, cur]
    }, [])
}      

參數

  • ​array​

    ​ 要去重的數組
  • ​key​

    ​ 要去重的對象屬性值

小栗子

const responseList = [
    { id: 1, a: 1 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
]

uniqueBy(responseList, 'id')

// => [ { id: 1, a: 1 }, { id: 2, a: 2 }, { id: 3, a: 3 } ]      

················· 若川簡介 ·················

你好,我是若川,畢業于江西高校。現在是一名前端開發“工程師”。寫有《學習源碼整體架構系列》20餘篇,在知乎、收獲超百萬閱讀。

從2014年起,每年都會寫一篇年度總結,已經寫了7篇,點選檢視年度總結。