亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JS生成嵌套數組

JS生成嵌套數組

一只斗牛犬 2018-09-10 13:19:00
比如$scope.colsNum=3,生成一個$scope._outArray=[[5],[5],[2]]這樣的數組。這里是想把$scope.testArray生成一個嵌套的數組,這樣也能實現,但覺得自己寫的太啰嗦了,希望給一個更好的寫法。
查看完整描述

1 回答

?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

用 lodash

如果用 lodash,很簡單,一個函數就搞定

const _ = require("lodash");const result = _.chunk(data, colsNum);console.log(result);

lodash 的 _.chunk() 源碼

回答完這個問題之后我突然好奇 lodash 是怎么實現的,所以我去翻了下它的源碼,其中最關鍵的一段是

  while (index < length) {
    result[resIndex++] = baseSlice(array, index, (index += size));
  }

可以看出來,它采用的是 slice 的思想,每次取一段出來放在新數組中。 slice 它調用的 baseSlice() 在 _baseSlice.js 中,對應 _.slice() 方法,,實現的功能和 Array.prototype.slice 一致。

這就有意思了,如果采用這種方式,就有辦法使用函數式與法了——見自己寫函數的第三個方法。

自己寫函數

reduce

當然自己寫也可以,之前回答某個問題的時候寫過,再寫一次,用 reduce 再稍加處理。

主要是保持兩個數組,一個是結果數組,一個是當前組數組,不需要 i 變量,因為當前組數組的 length 就能取到數量信息。

function groupByCols(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 = groupByCols(data, colsNum);console.log(result);

forEach

其實 reduce 用在這里優勢不明顯,因為有最后一步處理,不能直接返回結果。所以用和你的方法類似的 forEach改寫

function groupByCols2(data, cols) {    const list = [];    let current = [];
    data.forEach(t => {
        current.push(t);        if (current.length === cols) {
            list.push(current);
            current = [];
        }
    });    if (current.length) {
        list.push(current);
    }    return list;
}

slice + map 實現

為了函數式寫法,可能有些計算不太好理解,先看代碼

const result = Array.apply(null, {
    length: Math.ceil(data.length / cols)
}).map((x, i) => {    return data.slice(i * cols, i * cols + cols);
});

Array.apply 是為了生成一個長度為 Math.ceil(data.length / cols) 的數組,這就是循環次數(Math.ceil() 用于保證有余數則進1)。

然后在循環次數內通過 slice() 分段取出來。

用 RxJs

RxJs 用于異步處理數據還是挺方便的,用它的 bufferCount() 解決這種問題

const Rx = require("rxjs");const out = Rx.Observable.from(data)
    .bufferCount(colsNum)
    .toArray()
    .do(console.log)
    .subscribe();

這種方法適合異步或者 callback 處理(上面 console.log 那里傳入的你的數據處理函數。


查看完整回答
反對 回復 2018-10-28
  • 1 回答
  • 0 關注
  • 1949 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號