英文文章來源於:https://github.com/Chalarangelo/30-seconds-of-code/blob/master/README.mdgit
計算數字數組最大公約數 (gcd).github
用 Array.reduce()
和 gcd
運算式 (使用遞歸) 計算一個數字數組的最大公約數.數組
const arrayGcd = arr => { const gcd = (x, y) => !y ? x : gcd(y, x % y); return arr.reduce((a,b) => gcd(a,b)); } // arrayGcd([1,2,3,4,5]) -> 1 // arrayGcd([4,8,12]) -> 4
求數字數組的最小公倍數 (lcm).閉包
用 Array.reduce()
和 lcm
運算式 (使用遞歸) 計算一個數字數組的最小公倍數.app
const arrayLcm = arr =>{ const gcd = (x, y) => !y ? x : gcd(y, x % y); const lcm = (x, y) => (x*y)/gcd(x, y); return arr.reduce((a,b) => lcm(a,b)); } // arrayLcm([1,2,3,4,5]) -> 60 // arrayLcm([4,8,12]) -> 24
返回一個數組中的最大值。dom
使用 Math.max()
結合spread操做符 (...
) 去獲取數組中的最大值.函數
const arrayMax = arr => Math.max(...arr); // arrayMax([10, 1, 5]) -> 10
返回數組中的最小值.翻譯
用 Math.min()
集合spread操做符 (...
) 去獲取數組中的最小值.指針
const arrayMin = arr => Math.min(...arr); // arrayMin([10, 1, 5]) -> 1
將一個數組分紅指定長度的塊數組.rest
用 Array.from()
生成一個適當長度的塊數組,而後遍歷整個塊數組.
用 Array.slice()
分割原數組向塊數組中的塊中插入元素,塊的長度爲 size
.
若是原數組最終不能在進行分割,那麼這個塊將包含剩餘的全部元素.
const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); // chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]
將數組中的非真值移除.
用 Array.filter()
去移除非真值 (false
, null
, 0
, ""
, undefined
, and NaN
).
const compact = arr => arr.filter(Boolean); // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
注:Boolean的初始值爲false
計算一個值在數組中出現的次數.
用 Array.reduce()
去計算每次遇到的特定值的次數.
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); // countOccurrences([1,1,2,1,2,3], 1) -> 3
抹平數組(沒有嵌套的數組).
使用遞歸.
用 Array.concat()
拼接一個空數組 ([]
) 而後使用spread操做符 (...
) 去抹平數組.
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
返回的數組中元素來自於源數組,但不包含目標數組中的元素.
將目標數組轉化爲一個 Set
, 而後用 Array.filter()
過濾原數組返回不在目標數組中的元素.
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; // difference([1,2,3], [1,2,4]) -> [3]
const difference2 = (a, b) => a.filter(x => b.indexOf(x) === -1) // difference2([1,2,3], [1,2,4]) -> [3]
const difference2 = (a, b) => a.filter(x => !b.includes(x)) // difference2([1,2,3], [1,2,4]) -> [3]
返回的數組中元素來自於源數組和目標數組中的元素通過comp
後的元素.
用 Array.filter()
和 Array.find()
去找出合適的元素.
const differenceWith = (res, dest, comp) => res.filter(a => !dest.find(b => comp(a, b))) // differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]
數組去重.
用 ES6 Set
和 ...rest
操做符去除全部重複的元素.
const distinctValuesOfArray = arr => [...new Set(arr)]; // distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
移除數組中的元素直到func
返回 true
,返回使數組中剩餘的元素.
循環數組, 判斷func
是否返回 true
,若是否使用 Array.slice()
移除數組中的第一個元素,直到 function
返回 true
; 不然,直接返回數組.
const dropElements = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr.splice(0,1); return arr; }; // dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
const dropElements = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr.splice(0, 1); return arr; }; dropElements([4, 3, 2, 1], n => n >= 3)
移除數組中的元素若是func
返回 true
使用 Array.filter()
來進行數組過濾
const dropElements = (arr, func) => arr.filter(!func) dropElements([4, 3, 2, 1], n => n >= 3)
返回一個從用變去除 n
個元素的數組
若是 n
小於數組的長度用 Array.slice()
去分割數組,而後返回分割獲得的數組,不然返回一個空數組.
const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - n) : [] // dropRight([1,2,3]) -> [1,2] // dropRight([1,2,3], 2) -> [1] // dropRight([1,2,3], 42) -> []
const dropRight = (arr, n = 1) => n < arr.length ? arr.splice(0, arr.length - n) : [] // dropRight([1,2,3])
每遍歷 n
個元素,返回一個元素.
用 Array.filter()
去篩選出一個數組,篩選條件是每遍歷 n
個元素,返回一個元素.
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); // everyNth([1,2,3,4,5,6], 2) -> [ 2, 4, 6 ]
過濾移除數組中重複出現的元素.
用 Array.filter()
保留數組中獨一無二的元素.
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); // filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
抹平數組.
用一個空數組和spread ...
操做符來生成一個沒有嵌套的數組.
const flatten = arr => [].concat( ...arr ); // flatten([1,[2],3,4]) -> [1,2,3,4]
抹平數組取決於指定的值 depth
.
經過遞減 depth
,而後使用遞歸來完成.
用 Array.reduce()
和 Array.concat()
來合併元素或者數組.
默認 depth
值爲 1
時中止遞歸.
省略定義 depth
,將返回數組自己.
const flattenDepth = (arr, depth = 1) => depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), []) : arr.reduce((a, v) => a.concat(v), []); // flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]
根據給定的函數來對數組中的元素進行分組.
用 Array.map()
依據 func
來遍歷數組中的元素.
用 Array.reduce()
建立一個對象, 對象中的key是map的結果.
const groupBy = (arr, func) => arr.map(typeof func === 'function' ? func : val => val[func]) .reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}); // groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]} // groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
返回數組中的第一個元素.
用 arr[0]
返回傳入數組的第一個元素.
const head = arr => arr[0]; // head([1,2,3]) -> 1
返回數組中出最後一個外的全部元素.
用 arr.slice(0,-1)
來實現.
const initial = arr => arr.slice(0, -1); // initial([1,2,3]) -> [1,2]
經過傳入寬高和默認值來初始化一個二維數組.
用 Array.map()
去生成一個 h
列, 每列是一個長度爲 w
,默認值是 value
的數組的二維數組. 若是默認值沒有提供,那麼默認值就爲 null
.
const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val)); // initializeArrayWithRange(2, 2, 0) -> [[0,0], [0,0]]
初始化一個數組,這個數組包含限定範圍的數字 start
和 end
.
用 Array.from((end + 1) - start)
去建立一個長度爲end - start + 1
的數組,而後用Array.map()
爲初始化的數組賦值.
你能夠省略 start
,它的默認值是 0
.
const initializeArrayWithRange = (end, start = 0) => Array.from({ length: (end + 1) - start }).map((v, i) => i + start); // initializeArrayWithRange(5) -> [0,1,2,3,4,5] // initializeArrayWithRange(7, 3) -> [3,4,5,6,7]
初始化一個長度爲 n
數組,默認值爲 value
的數組.
用 Array(n)
去建立一個長度爲n,元素值爲空的數組,而後用 fill(v)
爲每一個元素賦值爲 value
.
若是省略 value
,元素的默認值爲 0
.
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); // initializeArrayWithValues(5, 2) -> [2,2,2,2,2]
返回兩個數組的共有元素.
將 b
轉換爲一個集合 Set
, 而後用 Array.filter()
過濾掉 a
中包含 b
中的元素.
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]
返回數組中的最後一個元素.
用 arr.length - 1
做爲給定數組最後一個元素的索引,返回該索引位置的元素.
const last = arr => arr[arr.length - 1]; // last([1,2,3]) -> 3
用一個函數做爲映射規則,將數組轉化爲一個對象, 對象的鍵值對由原始的的的值做爲鍵,映射獲得的值做爲值.
使用內部匿名函數的做用域去聲明一個undefined的內存空間, 用閉包去存儲返回值. 用一個新 Array
存儲原數組和通過 fn
映射的結果,而後用 ,
操做符實現下一步的return操做, 無需上下文的切換 (因爲閉包和操做順序).
const mapObject = (arr, fn) => (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,i) => (acc[val] = a[1][i], acc), {}) )) (); /* const squareIt = arr => mapObject(arr, a => a*a) squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } */
返回數組中的第 n
個元素.
用 Array.slice()
去得到包含第 n
個元素的數組,數組長度爲1.
若是索引超出數組範圍,返回一個 []
.
若是省略參數 n
, 默認的獲取數組的第一個元素.
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n,n+1) : arr.slice(n))[0]; // nthElement(['a','b','c'],1) -> 'b' // nthElement(['a','b','b'],-3) -> 'a'
從對象中篩選出arr
中指定的鍵值對.
用 Array.reduce()
去過濾並挑選出對象中所包含的鍵的鍵值對.
const pick = (obj, arr) => arr.reduce((acc, cur) => (cur in obj && (acc[cur] = obj[cur]), acc), {}); // pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
去除數組中的指定值.
用 Array.filter()
和 Array.includes()
清除數組中不須要的值.
用 Array.length = 0
初始化數組,而後用arr.push()放入過濾後剩餘的數組元素 pulled
.
const pull = (arr, ...args) => { let argState = Array.isArray(args[0]) ? args[0] : args; let pulled = arr.filter((v, i) => !argState.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; // let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c']; // pull(myArray1, 'a', 'c'); // console.log(myArray1) -> [ 'b', 'b' ] // let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c']; // pull(myArray2, ['a', 'c']); // console.log(myArray2) -> [ 'b', 'b' ]
過濾出指定索引的數組元素,並修改原數組.
用 Array.filter()
和 Array.includes()
提取不須要的元素.
用 Array.length = 0
初始化數組且長度爲零, 用 Array.push()
從新傳入剩餘的元素.
用 Array.push()
記錄pulled值
const pullAtIndex = (arr, pullArr) => { let removed = []; let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) .filter((v, i) => !pullArr.includes(i)) arr.length = 0; pulled.forEach(v => arr.push(v)); return removed; } // let myArray = ['a', 'b', 'c', 'd']; // let pulled = pullAtIndex(myArray, [1, 3]); // console.log(myArray); -> [ 'a', 'c' ] // console.log(pulled); -> [ 'b', 'd' ]
從原數組中過濾出指定元素. 返回過濾出的元素.
用 Array.filter()
和 Array.includes()
移除沒必要要的元素.
用 Array.length = 0
初始化元素組且長度爲零,用 Array.push()
從新傳入剩餘的元素.
用 Array.push()
記錄 pulled 值
const pullAtValue = (arr, pullArr) => { let removed = [], pushToRemove = arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v), mutateTo = arr.filter((v, i) => !pullArr.includes(v)); arr.length = 0; mutateTo.forEach(v => arr.push(v)); return removed; } /* let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtValue(myArray, ['b', 'd']); console.log(myArray); -> [ 'a', 'c' ] console.log(pulled); -> [ 'b', 'd' ] */
const pullAtValue = (arr, pullArr) => { let removed = []; arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v); pullArr.filter((v) => arr.splice(arr.indexOf(v), 1)); return removed; } /* let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtValue(myArray, ['b', 'd']); console.log(myArray); -> [ 'a', 'c' ] console.log(pulled); -> [ 'b', 'd' ] */
若是給定的函數返回 false
, 則從數組中移除元素.
用 Array.filter()
找返回 false
的數組元素,用 Array.reduce()
和 Array.splice()
對原數組進行處理.func
調用 (value, index, array
) 參數.
const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : []; // remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4]
從數組中返回一個隨機元素.
用 Math.random()
生成一個隨機數, 乘以數組的 length
,而後 Math.floor()
進行下舍入.
這個方法也適合字符串.
const sample = arr => arr[Math.floor(Math.random() * arr.length)]; // sample([3, 7, 9, 11]) -> 9
返回一個數組,數組元素在兩個給定的數組中均有.
用 filter()
過濾出不在另外一個數組中的 values
, 肯定條件用 includes()
.
const similarity = (arr, values) => arr.filter(v => values.includes(v)); // similarity([1,2,3], [1,2,4]) -> [1,2]
返回一個數組,包含在給定的兩個數組中均未出現的元素.
爲每一個數組建立一個 Set
, 而後用 Array.filter()
過濾剩下都有的元素.
const symmetricDifference = (a, b) => { const sA = new Set(a), sB = new Set(b); return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; } // symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
const symmetricDifference = (a, b) => [...(new Set([...a,...b]))].filter((v) => !a.includes(v) || !b.includes(v)); // symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
隨機化一個數組值的順序.
用 Array.sort()
從新排序數組 , 用 Math.random()
做比較器.
const shuffle = arr => arr.sort(() => Math.random() - 0.5); // shuffle([1,2,3]) -> [2,3,1]
返回數組中出第一個元素外的全部元素.
若是,數組 length
大於 1
返回 arr.slice(1)
,否者,返回整個數組.
const tail = arr => arr.length > 1 ? arr.slice(1) : arr; // tail([1,2,3]) -> [2,3] // tail([1]) -> [1]
返回指定長度的數組,數組中元素從數組第一個元素起.
用 Array.slice()
從原始數組的第一個元素起,截取 n
個元素.
const take = (arr, n = 1) => arr.slice(0, n); // take([1, 2, 3], 5) -> [1, 2, 3] // take([1, 2, 3], 0) -> []
返回指定長度的數組,數組中元素從數組最後一個元素起.
用 Array.slice()
從原始數組的最後一個元素起,截取 n
個元素.
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); // takeRight([1, 2, 3], 2) -> [ 2, 3 ] // takeRight([1, 2, 3]) -> [3]
返回兩個數組中存在的全部元素.
建立一個 Set
用 a
和 b
全部元素,而後轉換爲數組.
const union = (a, b) => Array.from(new Set([...a, ...b])); // union([1,2,3], [4,3,2]) -> [1,2,3,4]
從數組中移除全部指定的元素.
用 Array.filter()
過濾出全部制定的元素(用 !Array.includes()
作過濾條件 ).
(For a snippet that mutates the original array see pull
)
const without = (arr, ...args) => arr.filter(v => !args.includes(v)); // without([2, 1, 2, 3], 1, 2) -> [3]
建立一個數組,根據原始數組中的位置進行分組.
用 Math.max.apply()
得到參數中最長的數組的長度.
建立一個用該長度作返回值並使用 array.from
和 map()
建立分組的元素數組.
若是參數數組的長度不一樣, undefined
將被用於沒有元素的地方.
const zip = (...arrays) => { const maxLength = Math.max(...arrays.map(x => x.length)); return Array.from({length: maxLength}).map((_, i) => { return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); }) } //zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] //zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]
給定一個有效的屬性標識數組,返回一個屬性與值相關聯的對象.
由於對象能夠有未定義的值,但不能有未定義的屬性指針,因此使用 Array.reduce()
決定結果對象的結構.
const zipObject = ( props, values ) => props.reduce( ( obj, prop, index ) => ( obj[prop] = values[index], obj ), {} ) // zipObject(['a','b','c'], [1,2]) -> {a: 1, b: 2, c: undefined} // zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2}
更多關於30-seconds-code中文翻譯
https://github.com/lvzhenbang/article/blob/master/js/30-seconds-code/index.md