摘要:使用把指定運(yùn)算結(jié)果為的數(shù)組元素添加到二維數(shù)組的第一個(gè)數(shù)組中,運(yùn)算結(jié)果為的數(shù)組元素添加到二維數(shù)組的第二個(gè)數(shù)組中。所以改成了,它是不改變數(shù)組元素的,沒(méi)有副作用,不干擾后續(xù)。方法將剩余的所有數(shù)組元素以的方式返回結(jié)果數(shù)組。
原文地址:JavaScript30秒, 從入門(mén)到放棄之Array(四)maxN博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(四)
水平有限,歡迎批評(píng)指正
Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array"s length, then return the original array(sorted in descending order).
Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
返回一個(gè)數(shù)組的前n個(gè)最大值,如果指定的n大于或等于指定數(shù)組的長(zhǎng)度,那么將返回原數(shù)組(按降序排列后)。
使用Array.sort()和ES6的擴(kuò)展運(yùn)算符…來(lái)生成一個(gè)按降序排列的淺度復(fù)制數(shù)組。使用Array.slice()來(lái)截取指定個(gè)數(shù)的數(shù)組元素。若省略第二個(gè)參數(shù)n時(shí),n=1。
? code cat maxN.js const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); console.log(maxN([1, 2, 3])); console.log(maxN([1, 2, 3], 2)); ? code node maxN.js [ 3 ] [ 3, 2 ]
主要看懂這個(gè)sort就好了:
sort((a, b) => b - a)
這是降序排的方法,怎么講?
變形一:
sort(fn(a,b))
這個(gè)fn呢有兩個(gè)參數(shù)a、b就是數(shù)組排序是按順序相鄰的兩個(gè)數(shù)組元素。a前、b后。
變形二:
sort((a, b) => { if (b > a) { return 1; } else if (b < a) { return -1; } return 0; })
return1表示把前面的數(shù)a放后面,后面的數(shù)b在放前面;return0表示不換位置;return-1表示前面的數(shù)a放前面,后面的數(shù)b放后面。
例子中,當(dāng)b > a時(shí)把a換到b后面,意即把大數(shù)放前邊了,即降序排列。反之升序排列。
slice(0, n)
排完之后slice(0, n)截取前n個(gè)元素組成的數(shù)組即為數(shù)組最大的前n個(gè)數(shù)。
minNReturns the n minimum elements from the provided array. If n is greater than or equal to the provided array"s length, then return the original array(sorted in ascending order).
Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
返回一個(gè)數(shù)組的前n個(gè)最小值,如果指定的n大于或等于指定數(shù)組的長(zhǎng)度,那么將返回原數(shù)組(按升序排列后)。
使用Array.sort()和ES6的擴(kuò)展運(yùn)算符…來(lái)生成一個(gè)按升序排列的淺度復(fù)制數(shù)組。使用Array.slice()來(lái)截取指定個(gè)數(shù)的數(shù)組元素。若省略第二個(gè)參數(shù)n時(shí),n=1。
? code cat minN.js const maxN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); console.log(maxN([1, 2, 3])); console.log(maxN([1, 2, 3], 2)); ? code node minN.js [ 1 ] [ 1, 2 ]
sort((a, b) => a - b)與maxN相反,命題得證!
nthElementReturns the nth element of an array.
Use Array.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return []. Omit the second argument, n, to get the first element of the array.
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
返回指定數(shù)組的第n個(gè)元素(索引從0算起)。
使用Array.slice()截取數(shù)組,使截取的數(shù)組的第一個(gè)元素就是nth對(duì)應(yīng)的元素。如果索引n超過(guò)數(shù)組范圍,返回空數(shù)組[]。省略第二個(gè)參數(shù)n,按n=0計(jì)。
? code cat nthElement.js const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; console.log(nthElement(["a", "b", "c"], 1)); console.log(nthElement(["a", "b", "b"], -3)); ? code node nthElement.js b a
就是簡(jiǎn)單的用slice去截取元素,取截取后的第一個(gè)元素即可。
partitionGroups the elements into two arrays, depending on the provided function"s truthiness for each element.
Use Array.reduce() to create an array of two arrays. Use Array.push() to add elements for which fn returns true to the first array and elements for which fn returns false to the second one.
const partition = (arr, fn) => arr.reduce( (acc, val, i, arr) => { acc[fn(val, i, arr) ? 0 : 1].push(val); return acc; }, [[], []] );
根據(jù)提供的方法對(duì)一個(gè)數(shù)組就行調(diào)用后,按運(yùn)算結(jié)果的布爾值是否為真分類(lèi)。為真,歸到二維數(shù)組索引為0的數(shù)組中;為假,歸到二維數(shù)組索引為1的數(shù)組中。
使用Array.reduce()生成一個(gè)1x2的二維數(shù)組。使用Array.push()把指定fn運(yùn)算結(jié)果為true的數(shù)組元素添加到二維數(shù)組的第一個(gè)數(shù)組中,運(yùn)算結(jié)果為false的數(shù)組元素添加到二維數(shù)組的第二個(gè)數(shù)組中。
? code cat partition.js const partition = (arr, fn) => arr.reduce((acc, val, i, arr) => { acc[fn(val, i, arr) ? 0 : 1].push(val); return acc; }, [ [], [] ]); const users = [{ user: "Pony", age: 47, active: true }, { user: "barney", age: 36, active: false }, { user: "fred", age: 40, active: true }]; console.log(partition(users, o => o.active)); ? code node partition.js [ [ { user: "Pony", age: 47, active: true }, { user: "fred", age: 40, active: true } ], [ { user: "barney", age: 36, active: false } ] ]
acc的默認(rèn)值是一個(gè)1x2的二維空數(shù)組[[], []]。隨著reduce的遍歷過(guò)程將把滿足對(duì)應(yīng)條件的元素分別push到對(duì)應(yīng)的數(shù)組中。
acc[fn(val, i, arr) ? 0 : 1].push(val);
fn(val, i, arr)如果為true將會(huì)把對(duì)應(yīng)的元素val添加到acc的索引為0的數(shù)組中,否則添加到索引為1的數(shù)組中。這樣遍歷結(jié)束就達(dá)到了分組的目的。
例子中,fn是o => o.active就是根據(jù)對(duì)象的active的屬性是否為true進(jìn)行分類(lèi),所以我們看到,user為Pony和fred的元素都在二維數(shù)組的索引為0的數(shù)組中,其它在二維數(shù)組的索引為1的數(shù)組中。
pullMutates the original array to filter out the values specified.
Use Array.filter() and Array.includes() to pull out the values that are not needed. Use Array.length = 0 to mutate the passed in an array by resetting it"s length to zero and Array.push() to re-populate it with only the pulled values.
(For a snippet that does not mutate the original array see without)
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)); };
改變?cè)瓟?shù)組使其過(guò)濾掉指定的那些元素。
使用Array.filter()和Array.includes()剔除數(shù)組里不需要的元素。先用Array.length = 0把原數(shù)組變成空數(shù)組,然后再通過(guò)Array.push()把過(guò)濾后剩余的元素重新填充進(jìn)去。
(類(lèi)似方法不改變?cè)瓟?shù)組的請(qǐng)看without方法)
? code cat pull.js 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 myArray = ["a", "b", "c", "a", "b", "c"]; pull(myArray, "a", "c"); let secondArray = ["a", "b", "c", "a", "b", "c"]; pull(secondArray, ["a", "c"], "b"); console.log(myArray); console.log(secondArray); ? code node pull.js args: [ "a", "c" ] args: [ [ "a", "b" ], "c" ] [ "b", "b" ] [ "c", "c" ]
let argState = Array.isArray(args[0]) ? args[0] : args;
判斷args的第一個(gè)元素是不是一個(gè)數(shù)組,如果是,把該數(shù)組賦值給argState作為后續(xù)排除數(shù)組元素的元數(shù)組;否則args就是元數(shù)組。
let pulled = arr.filter((v, i) => !argState.includes(v));
結(jié)合filter和includes把數(shù)組arr中包含在argState中的元素排除掉。
arr.length = 0; pulled.forEach(v => arr.push(v));
此處,把數(shù)組長(zhǎng)度設(shè)為0,將數(shù)組置空,然后再遍歷pulled,把所有pulled的元素push到arr中,最終arr就只含有排除掉指定元素后的其他元素。
pullAtIndexMutates the original array to filter out the values at the specified indexes.
Use Array.filter() and Array.includes() to pull out the values that are not needed. Use Array.length = 0 to mutate the passed in an array by resetting it"s length to zero and Array.push() to re-populate it with only the pulled values. Use Array.push() to keep track of pulled values
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; };
改變?cè)瓟?shù)組使其過(guò)濾掉指定的那些索引值對(duì)應(yīng)的元素。
使用Array.filter()和Array.includes()剔除數(shù)組里不需要的元素。先用Array.length = 0把原數(shù)組變成空數(shù)組,然后再通過(guò)Array.push()把過(guò)濾后剩余的元素重新填充進(jìn)去。同時(shí)使用Array.push()跟蹤記錄剔除掉的所有元素。
? code cat pullAtIndex.js 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: ", myArray); console.log("pulled: ", pulled); ? code node pullAtIndex.js myArray: [ "a", "c" ] pulled: [ "b", "d" ]
let pulled = arr .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) .filter((v, i) => !pullArr.includes(i));
arr先map是為了把要排除掉的元素push到removed變量中。pullArr.includes(i) ? removed.push(v) : v這個(gè)三元運(yùn)算符就是判斷索引是否在要排除掉的指定索引數(shù)組pullArr中。如果在,添加到removed中,否則直接返回該元素。
接下來(lái)filter把arr中匹配pullArr的索引對(duì)應(yīng)元素剔除掉。
arr.length = 0; pulled.forEach((v) => arr.push(v)); return removed;
最后把arr置空后再填入滿足條件的元素,然后返回剔除掉的元素組成的數(shù)組。
pullAtValueMutates the original array to filter out the values specified. Returns the removed elements.
Use Array.filter() and Array.includes() to pull out the values that are not needed. Use Array.length = 0 to mutate the passed in an array by resetting it"s length to zero and Array.push() to re-populate it with only the pulled values. Use Array.push() to keep track of pulled values
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; };
改變?cè)瓟?shù)組使其過(guò)濾掉指定的那些值所匹配的元素們,返回剔除掉所有元素組成的數(shù)組。
使用Array.filter()和Array.includes()剔除數(shù)組里不需要的元素。先用Array.length = 0把原數(shù)組變成空數(shù)組,然后再通過(guò)Array.push()把過(guò)濾后剩余的元素重新填充進(jìn)去。同時(shí)使用Array.push()跟蹤記錄剔除掉的所有元素。
? code cat pullAtValue.js 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: ", myArray); console.log("pulled: ", pulled); ? code node pullAtValue.js myArray: [ "a", "c" ] pulled: [ "b", "d" ]
邏輯上和pullAtIndex差不多,差別就在一個(gè)是過(guò)濾索引,另一個(gè)是過(guò)濾值。
為此實(shí)現(xiàn)上就有了以下不同:
// pullAtIndex arr.map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) // pullAtValue arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v))
一個(gè)用了arr.map,一個(gè)用了arr.forEach。
為什么呢?
arr.map后arr的元素是會(huì)改變的,但是對(duì)于要剔除掉索引來(lái)說(shuō)要?jiǎng)h除掉索引對(duì)應(yīng)的值是否有變化是無(wú)關(guān)緊要的。而對(duì)于匹配值來(lái)說(shuō)就不靈了,因?yàn)楸緛?lái)要剔除掉的值在map的過(guò)程中改變了,到filter的時(shí)候就匹配不出來(lái)了,就無(wú)法剔除了。
所以改成了arr.forEach,它是不改變數(shù)組元素的,沒(méi)有副作用,不干擾后續(xù)filter。另外forEach的結(jié)果是undefined。
reducedFilterFilter an array of objects based on a condition while also filtering out unspecified keys.
Use Array.filter() to filter the array based on the predicate fn so that it returns the objects for which the condition returned a truthy value. On the filtered array, use Array.map() to return the new object using Array.reduce() to filter out the keys which were not supplied as the keys argument.
const reducedFilter = (data, keys, fn) => data.filter(fn).map(el => keys.reduce((acc, key) => { acc[key] = el[key]; return acc; }, {}) );
根據(jù)一個(gè)條件對(duì)一個(gè)數(shù)組進(jìn)行過(guò)濾,同時(shí)過(guò)濾掉不需要的鍵。
使用Array.filter()去過(guò)濾出指定方法fn對(duì)數(shù)組元素對(duì)象調(diào)用結(jié)果為真值的元素,對(duì)過(guò)濾后的數(shù)組使用Array.map()返回一個(gè)新的對(duì)象,對(duì)象包含的鍵值對(duì)是由Array.reduce()根據(jù)指定keys過(guò)濾掉不需要的鍵而組成的。
? code cat reducedFilter.js const reducedFilter = (data, keys, fn) => data.filter(fn).map(el => keys.reduce((acc, key) => { acc[key] = el[key]; return acc; }, {}) ); const data = [{ id: 1, name: "john", age: 24 }, { id: 2, name: "mike", age: 50 }]; console.log(reducedFilter(data, ["id", "name"], item => item.age > 24)); ? code node reducedFilter.js [ { id: 2, name: "mike" } ]
data.filter(fn)
數(shù)組data根據(jù)方法fn過(guò)濾掉了不滿足條件的數(shù)組元素。
keys.reduce((acc, key) => { acc[key] = el[key]; return acc; }, {})
keys是最終要保留的鍵的數(shù)組,reduce的acc初始值是空對(duì)象{},遍歷過(guò)程中,把所有的el對(duì)象中鍵包含于keys數(shù)組所有鍵值對(duì)累加到acc對(duì)象中。
map(el => fn1)
最后聯(lián)合map方法可以看出,最終返回的是一個(gè)數(shù)組,數(shù)組內(nèi)包含fn1方法也就是keys.reduce方法返回的acc的對(duì)象。
removeRemoves elements from an array for which the given function returns false.
Use Array.filter() to find array elements that return truthy values and Array.reduce() to remove elements using Array.splice(). The func is invoked with three arguments (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); }, []) : [];
刪除數(shù)組中以指定方法調(diào)用結(jié)果為false的所有元素。
使用Array.filter()來(lái)找出數(shù)組中所有運(yùn)行指定方法結(jié)果為真的元素,使用Array.reduce()配合Array.splice()刪除掉不需要的元素。func函數(shù)調(diào)用有三個(gè)參數(shù)(value, index, array)。
? code cat remove.js const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : []; const arr = [1,2,3,4]; console.log(remove(arr, n => n % 2 == 0)); console.log(arr); ? code node remove.js [ 2, 4 ] [ 1, 3 ]
Array.isArray(arr) ? filterfun : [];
先判斷給定參數(shù)arr是否是一個(gè)數(shù)組,是,執(zhí)行filter函數(shù);否,直接返回結(jié)果空數(shù)組[]。
arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, [])
arr.filter(func)首先過(guò)濾出func運(yùn)行結(jié)果為真所有數(shù)組元素。reduce方法將filter剩余的所有數(shù)組元素以concat的方式返回結(jié)果數(shù)組。而在原數(shù)組arr中,則用splice將func運(yùn)行結(jié)果為真的所有元素剔除。
其實(shí)就最終的返回結(jié)果來(lái)說(shuō),arr.filter(func)已經(jīng)可以返回正確的結(jié)果,之所以看起來(lái)多此一舉的使用了reduce的原因在于必須把不需要的元素從原數(shù)組arr中剔除。
以下是我在沒(méi)看代碼之前根據(jù)例子運(yùn)行結(jié)果先寫(xiě)的代碼:
? code cat remove1.js const remove = (arr, fn) => { let removed = []; arr.forEach(v => (fn(v) ? removed.push(v) : v)); const left = arr.filter(v => !fn(v)); arr.length = 0; left.forEach(v => arr.push(v)); return removed; }; const arr = [1,2,3,4]; console.log(remove(arr, n => n % 2 == 0)); console.log(arr); ? code node remove1.js [ 2, 4 ] [ 1, 3 ]
我認(rèn)為代碼本身應(yīng)該沒(méi)什么問(wèn)題,但可能沒(méi)那么優(yōu)雅,另外就是沒(méi)有做Array.isArray的前置條件判斷。
sampleReturns a random element from an array.
Use Math.random() to generate a random number, multiply it by length and round it of to the nearest whole number using Math.floor(). This method also works with strings.
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
返回?cái)?shù)組中隨機(jī)的一個(gè)元素。
使用Math.random()生成一個(gè)隨機(jī)數(shù),乘以數(shù)組的長(zhǎng)度,然后再配以Math.floor()獲取整數(shù)索引,進(jìn)而返回該索引對(duì)應(yīng)的數(shù)組元素。這個(gè)方法也同樣適用于字符串。
? code cat sample.js const sample = (arr) => arr[Math.floor(Math.random() * arr.length)] console.log(sample([3, 7, 9, 11])); ? code node sample.js 7
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/92635.html
摘要:循環(huán)一個(gè)數(shù)組,使用每次去刪除該數(shù)組的第一個(gè)元素直到指定方法運(yùn)算結(jié)果為,返回的是剩余元素組成的數(shù)組。直到循環(huán)退出,返回此時(shí)的。對(duì)應(yīng)就是,包含下界,不包含上屆。秒,從入門(mén)到放棄之二微信公眾號(hào)秒,從入門(mén)到放棄之二 difference Returns the difference between two arrays. Create a Set from b, then use Array...
摘要:原文地址秒,從入門(mén)到放棄之五博客地址秒,從入門(mén)到放棄之五水平有限,歡迎批評(píng)指正從給定的數(shù)組中隨機(jī)選出指定個(gè)數(shù)的數(shù)組元素。否則判斷數(shù)組元素是否大于或者等于指定元素,尋找過(guò)程與前邊類(lèi)似。 原文地址:JavaScript30秒, 從入門(mén)到放棄之Array(五)博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(五) 水平有限,歡迎批評(píng)指正 sampleSize Gets n...
摘要:否則,直接循環(huán)去拼接該值返回按照指定的方法對(duì)數(shù)組元素進(jìn)行分組歸類(lèi)。使用創(chuàng)建一個(gè)對(duì)象,對(duì)象的鍵是生成的結(jié)果,值是符合該鍵的所有數(shù)組元素組成的數(shù)組。微信公眾號(hào)秒,從入門(mén)到放棄之三 原文鏈接:JavaScript30秒, 從入門(mén)到放棄之Array(三)水平有限,歡迎批評(píng)指正 flattenDepth Flattens an array up to the specified depth....
摘要:從數(shù)組索引為開(kāi)始刪除元素,直到對(duì)數(shù)組元素運(yùn)用指定方法為為止。對(duì)兩個(gè)數(shù)組的元素分別調(diào)用指定方法后,返回以運(yùn)行結(jié)果為判定基準(zhǔn)的并集,并集是原始數(shù)組元素的并集而不是運(yùn)行結(jié)果的并集。 原文地址:JavaScript30秒, 從入門(mén)到放棄之Array(六)博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(六) 水平有限,歡迎批評(píng)指正 tail Returns all elem...
摘要:地址秒,從入門(mén)到放棄之七博客地址秒,從入門(mén)到放棄之七水平有限,歡迎批評(píng)指正剔除掉數(shù)組中所有存在于所指定的元素們的項(xiàng)。使用,和來(lái)創(chuàng)建由兩個(gè)數(shù)組元素拼接而成的所有可能對(duì)并將它們存在一個(gè)數(shù)組中的數(shù)組。 GitHub地址:JavaScript30秒, 從入門(mén)到放棄之Array(七)博客地址:JavaScript30秒, 從入門(mén)到放棄之Array(七) 水平有限,歡迎批評(píng)指正 without ...
閱讀 2447·2021-11-15 11:36
閱讀 1189·2019-08-30 15:56
閱讀 2252·2019-08-30 15:53
閱讀 1051·2019-08-30 15:44
閱讀 663·2019-08-30 14:13
閱讀 1005·2019-08-30 10:58
閱讀 486·2019-08-29 15:35
閱讀 1307·2019-08-29 13:58