javascript
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ù)組元素調用指定方法或者調用返回該元素的屬性值的方法。使用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' ] }代碼拆分:
對第二個參數(shù)func的類型進行判斷,若是function,則對數(shù)組arr所有元素調用該方法,返回一個新的數(shù)組。如:
const arr = [1, 2, 3, 4]; arr.map(x => x * x); // [1, 4, 9, 16]否則,調用返回該元素對應func屬性值方法:
const arr = ['one', 'two', 'three']; const func = 'length'; arr.map(val => val[func]); // [3, 3, 5]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ù)組中作為該鍵的值。最終返回一個分好類的對象。
head
Returns 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)立竿見影,實在沒啥可說。
initialize2DArray
Initializes 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ù)組并將它們全部默認填充為undefined。然后在生成的數(shù)組基礎上,每個數(shù)組元素調用一個生成w個元素的數(shù)組且每個位置的值都填充為val方法。這樣就生成了h行w列的二維數(shù)組。
initializeArrayWithRange
Initializes 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開始遞增。
initializeArrayWithValues
Initializes 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)一步到位,沒啥可說的了。
intersection
Returns 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ù)組。
last
Returns 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ù)組調用指定的方法后生成一個對象,對象的鍵是數(shù)組的元素值,對象的值是該元素值調用指定方法后生成的結果。
使用內部匿名函數(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調用fn后的map結果數(shù)組。然后去reduce生成以arr元素值為對象鍵(即val,也即a[0]數(shù)組遍歷過程中的元素值),以對應該元素值調用fn后的結果值(即a[1][ind])為對象值的對象。這個對象就是最終想要的結果。
一個時間處理庫:now.js,覺得還行的話,點個贊再走唄。。。
微信公眾號:JavaScript30秒, 從入門到放棄之Array(三)
總結
以上是生活随笔為你收集整理的JavaScript30秒, 从入门到放弃之Array(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 农商银行自助存款步骤 怎么用农商银行自助
- 下一篇: iOS开发之Objective-C与Ja