摘要:否則,直接循環(huán)去拼接該值返回按照指定的方法對數(shù)組元素進行分組歸類。使用創(chuàng)建一個對象,對象的鍵是生成的結果,值是符合該鍵的所有數(shù)組元素組成的數(shù)組。微信公眾號秒,從入門到放棄之三
原文鏈接:JavaScript30秒, 從入門到放棄之Array(三)flattenDepth水平有限,歡迎批評指正
Flattens an array up to the specified depth.
Use recursion, decrementing depth by 1 for each level of depth. Use Array.reduce() and Array.concat() to merge elements or arrays. Base case, for depth equal to 1 stops recursion. Omit the second element, depth to flatten only to a depth of 1 (single flatten).
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), []);
把一個數(shù)組按指定深度進行攤平。
使用遞歸方法,對于任意級別的深度depth,每次遞歸depth減1。使用Array.reduce()和Array.concat()來合并元素們或者數(shù)組們。直到depth遞減到1時停止遞歸。省略第二個參數(shù)depth時,按深度depth為1計(即單層攤平)。
? code cat flattenDepth.js 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), []); console.log(flattenDepth([1, [2], 3, 4])); console.log(flattenDepth([1, [2, [5]], 3, 4])); ? code node flattenDepth.js [ 1, 2, 3, 4 ] [ 1, 2, [ 5 ], 3, 4 ]
根據(jù)depth來決定處理流程,若depth存在且不等于1則進行遞歸:
arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
用了reduce()去處理循環(huán)時的每一個值,同時用concat把所有遞歸結果拼接成新數(shù)組返回。循環(huán)過程中,對值進行數(shù)組判斷Array.isArray(v),是數(shù)組,flattenDepth(v, depth - 1)深度減1繼續(xù)遞歸直到depth為1為止;不是數(shù)組,直接返回該值v,供concat拼接。
否則,直接循環(huán)去拼接該值返回:
arr.reduce((a, v) => a.concat(v), []);groupBy
Groups the elements of an array based on the given function.
Use Array.map() to map the values of an array to a function or property name. Use Array.reduce() to create an object, where the keys are produced from the mapped results.
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; }, {});
按照指定的方法對數(shù)組元素進行分組歸類。
使用Array.map()對所有數(shù)組元素調(diào)用指定方法或者調(diào)用返回該元素的屬性值的方法。使用Array.reduce()創(chuàng)建一個對象,對象的鍵是map生成的結果,值是符合該鍵的所有數(shù)組元素組成的數(shù)組。
? code cat groupBy.js 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; }, {}); console.log(groupBy([6.1, 4.2, 6.3], Math.floor)); console.log(groupBy(["one", "two", "three"], "length")); ? code node groupBy.js { "4": [ 4.2 ], "6": [ 6.1, 6.3 ] } { "3": [ "one", "two" ], "5": [ "three" ] }
代碼拆分:
map
arr.map(typeof func === "function" ? func : val => val[func])
對第二個參數(shù)func的類型進行判斷,若是function,則對數(shù)組arr所有元素調(diào)用該方法,返回一個新的數(shù)組。如:
const arr = [1, 2, 3, 4]; arr.map(x => x * x); // [1, 4, 9, 16]
否則,調(diào)用返回該元素對應func屬性值方法:
const arr = ["one", "two", "three"]; const func = "length"; arr.map(val => val[func]); // [3, 3, 5]
reduce
reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {})
acc是reduce過程中累積的結果,val是reduce的主體(即前邊map的結果數(shù)組)每次循環(huán)時數(shù)組元素的值,i則是主體數(shù)組循環(huán)時對應的索引。
第一個循環(huán)時acc的初始值是一個空對象{},循環(huán)過程中先判斷是否已經(jīng)有以val為鍵的值,如果還沒有,創(chuàng)建一個空數(shù)組把此時對應索引i的數(shù)組值arr[i]拼接,作為以val為鍵的值;否則,直接拼接arr[i]。即是acc[val] = (acc[val] || []).concat(arr[i])做的事。每次循環(huán)都返回acc對象,直到循環(huán)結束,生成分類結果。
連起來就是說先對數(shù)組arr元素進行map,map結果作為鍵,所有map結果相同的數(shù)組元素arr[i]歸到一個數(shù)組中作為該鍵的值。最終返回一個分好類的對象。
headReturns the head of a list.
Use arr[0] to return the first element of the passed array.
const head = arr => arr[0];
返回數(shù)組第一個元素。
使用arr[0]返回指定數(shù)組arr的第一個元素。
? code cat head.js const head = arr => arr[0]; console.log(head([1, 2, 3])); ? code node head.js 1initial
Returns all the elements of an array except the last one.
Use arr.slice(0,-1) to return all but the last element of the array.
const initial = arr => arr.slice(0, -1);
返回除數(shù)組最后一個元素外的所有元素組成的新數(shù)組。
使用arr.slice(0, -1)返回數(shù)組除最后一個元素外的所有元素。
? code cat initial.js const initial = arr => arr.slice(0, -1); console.log(initial([1, 2, 3])); ? code node initial.js [ 1, 2 ]
arr.slice(0, -1)立竿見影,實在沒啥可說。
initialize2DArrayInitializes a 2D array of given width and height and value.
Use Array.map() to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to null.
const initialize2DArray = (w, h, val = null) => Array(h) .fill() .map(() => Array(w).fill(val));
初始化一個給定寬(列)、高(行)和值的二維數(shù)組。
使用Array.map()來生成一個h行的數(shù)組。每一行含有w個值為指定值的元素。如果未指定任何值,數(shù)組的默認值是null。
? code cat initialize2DArray.js const initialize2DArray = (w, h, val = null) => Array(h).fill().map(() => Array(w).fill(val)); console.log(initialize2DArray(2, 2, 0)); ? code node initialize2DArray.js [ [ 0, 0 ], [ 0, 0 ] ]
Array(h).fill()先創(chuàng)建一個含有h個元素的數(shù)組并將它們?nèi)磕J填充為undefined。然后在生成的數(shù)組基礎上,每個數(shù)組元素調(diào)用一個生成w個元素的數(shù)組且每個位置的值都填充為val方法。這樣就生成了h行w列的二維數(shù)組。
initializeArrayWithRangeInitializes an array containing the numbers in the specified range where start and end are inclusive.
Use Array((end + 1) - start) to create an array of the desired length, Array.map() to fill with the desired values in a range. You can omit start to use a default value of 0.
const initializeArrayWithRange = (end, start = 0) => Array.from({ length: end + 1 - start }).map((v, i) => i + start);
初始化一個包含start和end的有序數(shù)值的數(shù)組。
使用Array((end + 1) - start)生成所期望的數(shù)組,使用Array.map()去填充所期望的有序的數(shù)值。若省略start,則start默認值為0。
? code cat initializeArrayWithRange.js const initializeArrayWithRange = (end, start = 0) => Array.from({ length: end + 1 - start }).map((v, i) => i + start); console.log(initializeArrayWithRange(5)); console.log(initializeArrayWithRange(7, 3)); ? code node initializeArrayWithRange.js [ 0, 1, 2, 3, 4, 5 ] [ 3, 4, 5, 6, 7 ]
{length: end + 1 - start}生成的數(shù)組長度是end + 1 -start,而(v, i) => i + start按i從0開始循環(huán),直到length - 1為止。而i + start則表示元素值從0 + start開始遞增。
initializeArrayWithValuesInitializes and fills an array with the specified values.
Use Array(n) to create an array of the desired length, fill(v) to fill it with the desired values. You can omit value to use a default value of 0.
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
初始化一個數(shù)組并全部填充指定值。
Array(n)生成期望長度的數(shù)組,fill(v)填充期望的值。若省略第二個參數(shù)value,則value默認為0。
? code cat initializeArrayWithValues.js const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); console.log(initializeArrayWithValues(5, 2)); ? code node initializeArrayWithValues.js [ 2, 2, 2, 2, 2 ]
Array(n).fill(value)一步到位,沒啥可說的了。
intersectionReturns a list of elements that exist in both arrays.
Create a Set from b, then use Array.filter() on a to only keep values contained in b.
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); };
返回兩個數(shù)組的交集。
首先創(chuàng)建一個b數(shù)組的集合,然后使用Array.filter()去篩選出a數(shù)組中存在于b數(shù)組中的元素。
? code cat intersection.js const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; console.log(intersection([1, 2, 3], [4, 3, 2])); ? code node intersection.js [ 2, 3 ]
const s = new Set(b)先用集合把b數(shù)組去重,然后a.filter(x => s.has(x))過濾數(shù)組a,返回所有存在于s集合中元素組成的數(shù)組。
lastReturns the last element in an array.
Use arr.length - 1 to compute the index of the last element of the given array and returning it.
const last = arr => arr[arr.length - 1];
返回數(shù)組的最后一個元素。
用arr.length - 1去計算一個數(shù)組最后一個元素的索引值并返回其對應的數(shù)組元素。
? code cat last.js const last = arr => arr[arr.length - 1]; console.log(last([1, 2, 3])); ? code node last.js 3mapObject
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new Array to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
const mapObject = (arr, fn) => (a => ( (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) ))();
把一個數(shù)組調(diào)用指定的方法后生成一個對象,對象的鍵是數(shù)組的元素值,對象的值是該元素值調(diào)用指定方法后生成的結果。
使用內(nèi)部匿名函數(shù)定義一個不污染全局變量的命名空間并用閉包存儲返回值。使用一個新的數(shù)組來存儲一個包含arr數(shù)組和arr數(shù)組去map指定方法后生成的數(shù)組。并在前面數(shù)組的基礎上借助,運算符去一步步的生成所需要的對象。避免了上下文環(huán)境context來回轉換(得益于閉包和運算順序)。 (這塊不是太懂)
? code cat mapObject.js const mapObject = (arr, fn) => (a => ( (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) ))(); const squareIt = arr => mapObject(arr, a => a * a); console.log(squareIt([1, 2, 3])); ? code node mapObject.js { "1": 1, "2": 4, "3": 9 }
逗號運算符會返回最后一個運算表達式運算的結果,如:
const i = 0 i + 1, i // i = 1
即先進行i + 1運算,為1,然后返回i即1。
以上代碼含有兩個逗號運算表達式:
((acc[val] = a[1][ind]), acc)
即先做(acc[val] = a[1][ind])這個運算,然后返回acc。
第二個是:
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
即在a = [arr, arr.map(fn)]定義了a的基礎上去運用后面的reduce方法,最后返回reduce方法的結果。
可以看出,先定義了一個長度為2的數(shù)組a,索引0對應值為數(shù)組arr,索引1對應值為數(shù)組arr調(diào)用fn后的map結果數(shù)組。然后去reduce生成以arr元素值為對象鍵(即val,也即a[0]數(shù)組遍歷過程中的元素值),以對應該元素值調(diào)用fn后的結果值(即a[1][ind])為對象值的對象。這個對象就是最終想要的結果。
一個時間處理庫:now.js,覺得還行的話,點個贊再走唄。。。
微信公眾號:JavaScript30秒, 從入門到放棄之Array(三)
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://m.hztianpu.com/yun/90558.html
摘要:循環(huán)一個數(shù)組,使用每次去刪除該數(shù)組的第一個元素直到指定方法運算結果為,返回的是剩余元素組成的數(shù)組。直到循環(huán)退出,返回此時的。對應就是,包含下界,不包含上屆。秒,從入門到放棄之二微信公眾號秒,從入門到放棄之二 difference Returns the difference between two arrays. Create a Set from b, then use Array...
摘要:原文地址秒,從入門到放棄之五博客地址秒,從入門到放棄之五水平有限,歡迎批評指正從給定的數(shù)組中隨機選出指定個數(shù)的數(shù)組元素。否則判斷數(shù)組元素是否大于或者等于指定元素,尋找過程與前邊類似。 原文地址:JavaScript30秒, 從入門到放棄之Array(五)博客地址:JavaScript30秒, 從入門到放棄之Array(五) 水平有限,歡迎批評指正 sampleSize Gets n...
摘要:從數(shù)組索引為開始刪除元素,直到對數(shù)組元素運用指定方法為為止。對兩個數(shù)組的元素分別調(diào)用指定方法后,返回以運行結果為判定基準的并集,并集是原始數(shù)組元素的并集而不是運行結果的并集。 原文地址:JavaScript30秒, 從入門到放棄之Array(六)博客地址:JavaScript30秒, 從入門到放棄之Array(六) 水平有限,歡迎批評指正 tail Returns all elem...
摘要:地址秒,從入門到放棄之七博客地址秒,從入門到放棄之七水平有限,歡迎批評指正剔除掉數(shù)組中所有存在于所指定的元素們的項。使用,和來創(chuàng)建由兩個數(shù)組元素拼接而成的所有可能對并將它們存在一個數(shù)組中的數(shù)組。 GitHub地址:JavaScript30秒, 從入門到放棄之Array(七)博客地址:JavaScript30秒, 從入門到放棄之Array(七) 水平有限,歡迎批評指正 without ...
摘要:三元運算符遍歷過程中判斷遍歷數(shù)組值是否嚴格等于指定值,是,次數(shù)否,。三元運算符判斷是否是一個數(shù)組,是,返回遞歸運用后的值否,直接返回。秒,從入門到放棄博客地址秒,從入門到放棄微信公眾號地址秒,從入門到放棄 有意思 最近很火的github上的庫30-seconds-of-code,特別有意思,代碼也很優(yōu)雅。 能學es6 自己翻譯,能學英語 代碼很美,很優(yōu)雅,美即正義 函數(shù)式表達,享受 ...
閱讀 3181·2019-08-30 15:56
閱讀 1303·2019-08-29 15:20
閱讀 1638·2019-08-29 13:19
閱讀 1573·2019-08-29 13:10
閱讀 3454·2019-08-26 18:27
閱讀 3128·2019-08-26 11:46
閱讀 2307·2019-08-26 11:45
閱讀 3947·2019-08-26 10:12