今天回答了 @_bleach 的問題:JS生產(chǎn)嵌套數(shù)組(也就是對數(shù)組分組)更好的寫法。回答的過程中對 lodash
_.chunk()
產(chǎn)生了好奇,所以分析了一下它的源碼,再加上我自己的解決方案,收集了如下一些方案,分享給大家按慣例,我還是使用 es6 語法,在 Node7 中實驗通過
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const groupByNum = 3;
因為最近在學習 RxJs,所以順手做了個 RxJs 解決方案。但這不是重點。不了解或者很了解 RxJs 的請忽略。
RxJava 很火,其實 ReactiveX 有很多種語言的實現(xiàn),JavaScript 的實例就是 RxJs,建議學習的同學直接上 5.0 Beta。不過 RxJs 主要用于異步流處理,所以需要通過回調(diào)函數(shù)來使用結(jié)果。
const Rx = require("rxjs");
const out = Rx.Observable.from(data)
.bufferCount(groupByNum)
.toArray()
.do((result) => {
console.log(result)
})
.subscribe();
上面的 do()
一句可以直接寫成 do(console.log)
,寫成現(xiàn)在這樣的目的是為了讓大家看到計算結(jié)果在哪。
lodash 提供了大量數(shù)據(jù)處理的方法,_.chunk()
專為分組而生
const _ = require("lodash");
const result = _.chunk(data, groupByNum);
在 node 環(huán)境也,通過 npm 安裝 lodash 之后就能在 node_modules/lodash
目錄下找到源碼文件 chunk.js
npm install lodash
所以完整的源碼不貼了,只看下關(guān)鍵的那一句
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
baseSlice()
是 lodash 對 Array.prototype.slice()
的兼容性實現(xiàn),可以直接當 slice()
來看??戳诉@個源碼,我有了函數(shù)式寫法的思路,后面通過 slice() + map()
實現(xiàn)部分詳述。
像這種,目標數(shù)組長度和原數(shù)組長度不一致的情況,函數(shù)式寫法很容易想到 reduce()
函數(shù)。只可惜單純的 reduce()
做不出來(在 data.length
不能被 groupByNum
整除的時候)
function groupArray(data, cols) {
const r = data.reduce((r, t) => {
r.current.push(t);
if (r.current.length === cols) {
r.list.push(r.current);
r.current = [];
}
return r;
}, { list: [], current: [] });
if (r.current.length) {
r.list.push(r.current);
}
return r.list;
}
const result = groupArray(data, groupByNum);
reduce()
的初始化對象是 { list: [], current: [] }
,其中 list
是要得計算出來的結(jié)果,而 current
是中間變量,用于生成每個組。
最后由于不有保證 data.length
一定被 groupByNum
整除,所以可能會有一個未完成的 current
沒被 push 到 list
當中,所以專門進行了一個判斷和處理。因此不能寫成函數(shù)式寫法,有些遺憾。
既然不能用函數(shù)式寫法,那 forEach()
或者 for ... of
實現(xiàn)就會更容易理解一些。
function groupArray(data, cols) {
const list = [];
let current = [];
// for (t of data) {
data.forEach(t => {
current.push(t);
if (current.length === cols) {
list.push(current);
current = [];
}
});
// } // for (t of data)
if (current.length) {
list.push(current);
}
return list;
}
看到了 _.chunk()
的源碼,讓我產(chǎn)生了函數(shù)式寫法的靈感,相比上面的解決方案,更難于理解,不過語法看起來很酷
const result = Array.apply(null, {
length: Math.ceil(data.length / groupByNum)
}).map((x, i) => {
return data.slice(i * groupByNum, (i + 1) * groupByNum);
});
Array.apply()
是為了生成一個長度為 Math.ceil(data.length / groupByNum)
的數(shù)組作為 map()
的源,map()
不需要這個源的數(shù)據(jù),只需要這個源每個數(shù)組的 index
。
Math.ceil()
用于保證在除法計算有余數(shù)的時候?qū)ι?+1,即循環(huán)次數(shù) +1。
然后在算得的循環(huán)次數(shù)中,通過 slice
返回每一段結(jié)果,通過 map()
映射出來,最終生成需要的結(jié)果。
數(shù)組分組是一個很簡單的問題,有很多種方法來處理。本文并不是想告訴大家如何處理這個問題,而是將我處理問題的思路分享出來,希望能對處理各種數(shù)據(jù)問題帶來一點點啟發(fā)。
更多建議: