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

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

使用 JavaScript 混合數組

使用 JavaScript 混合數組

胡說叔叔 2022-01-01 20:42:54
混合多個數組的最佳方法是什么,如下圖所示,PS:我不知道每個數組的長度是多少數組將包含 +10000 個元素將有 3 個以上的數組我為它制定了一個解決方案,但我正在尋找任何更好的解決方案這是我自己的解決方案,我正在尋找更好的主意import { compact, flattenDeep } from "lodash/array";export const doTheMagic = master => {  const longest = master.reduce((p, c, i, a) => (a[p].length > c.length ? p : i), 0);  const mixed = master[longest].map((i, k) => {    return master.map((o, a) => {      if (master[a][k]) return master[a][k];    });  });  const flaten = flattenDeep(mixed);  return  compact(flaten);// to remove falsey values};const one = [1,2,3];const two = ['a','b','c','d','e'];const three = ['k','l','m','n'];const mix = doTheMagic([one,two,three]);console.log('mix: ', mix);
查看完整描述

3 回答

?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

您可以使用 lodash 作為您的解決方案。


const { flow, zip, flatten, filter} = _


const doTheMagic = flow(

  zip,

  flatten,

  filter

)


const one = [1, 2, 3]

const two = ['??', '??', '??', '??', '??', '??']

const three = ['foo', 'bar', 'wow', 'okay']


const result = doTheMagic(one, two, three)


console.log(result)

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>


處理不同長度的數組,并利用函數式編程來編寫優雅的代碼。


這是一個要運行的代碼筆:https ://codepen.io/matteodem/pen/mddQrwe


查看完整回答
反對 回復 2022-01-01
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

let a1 = [1, 2, 3, 4, 5];

let a2 = ["??", "??", "??", "??", "??", "??"];

let a3 = ['one', 'two', 'three', 'four', 'five'];


const doTheMagic = arrayOfArrays => {

  let maxLength = 0;

  let result = [];

  for (arr in arrayOfArrays) {

    maxLength = Math.max(maxLength, arrayOfArrays[arr].length);

  }

  for (let i = 0; i < maxLength; i++) {

    for (let j = 0; j < arrayOfArrays.length; j++) {

      if (arrayOfArrays[j][i]) {

        result.push(arrayOfArrays[j][i]);

      }

    }

  }

  return result;

}


console.log(doTheMagic([a1, a2, a3]));


查看完整回答
反對 回復 2022-01-01
?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

這是我自己的解決方案,我正在尋找更好的主意


import { compact, flattenDeep } from "lodash/array";


export const doTheMagic = master => {

  const longest = master.reduce((p, c, i, a) => (a[p].length > c.length ? p : i), 0);

  const mixed = master[longest].map((i, k) => {

    return master.map((o, a) => {

      if (master[a][k]) return master[a][k];

    });

  });

  const flaten = flattenDeep(mixed);

  return  compact(flaten);// to remove falsey values

};

const one = [1,2,3];

const two = ['a','b','c','d','e'];

const three = ['k','l','m','n'];

const mix = doTheMagic([one,two,three]);

console.log('mix: ', mix);


查看完整回答
反對 回復 2022-01-01
  • 3 回答
  • 0 關注
  • 283 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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