使用 JavaScript 混合数组

混合多个数组的最佳方法是什么,如下图所示,

PS:

  • 我不知道每个数组的长度是多少

  • 数组将包含 +10000 个元素

  • 将有 3 个以上的数组

我为它制定了一个解决方案,但我正在寻找任何更好的解决方案

http://img4.mukewang.com/61d04c7b0001873b06460293.jpg

这是我自己的解决方案,我正在寻找更好的主意


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);


胡说叔叔
浏览 254回答 3
3回答

狐的传说

您可以使用 lodash 作为您的解决方案。const { flow, zip, flatten, filter} = _const doTheMagic = flow(&nbsp; zip,&nbsp; flatten,&nbsp; 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/lodash@4.17.15/lodash.min.js"></script>处理不同长度的数组,并利用函数式编程来编写优雅的代码。这是一个要运行的代码笔:https ://codepen.io/matteodem/pen/mddQrwe

四季花海

let a1 = [1, 2, 3, 4, 5];let a2 = ["🏯", "🏜", "🏭", "🎢", "🌠", "🏗"];let a3 = ['one', 'two', 'three', 'four', 'five'];const doTheMagic = arrayOfArrays => {&nbsp; let maxLength = 0;&nbsp; let result = [];&nbsp; for (arr in arrayOfArrays) {&nbsp; &nbsp; maxLength = Math.max(maxLength, arrayOfArrays[arr].length);&nbsp; }&nbsp; for (let i = 0; i < maxLength; i++) {&nbsp; &nbsp; for (let j = 0; j < arrayOfArrays.length; j++) {&nbsp; &nbsp; &nbsp; if (arrayOfArrays[j][i]) {&nbsp; &nbsp; &nbsp; &nbsp; result.push(arrayOfArrays[j][i]);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; return result;}console.log(doTheMagic([a1, a2, a3]));

慕沐林林

这是我自己的解决方案,我正在寻找更好的主意import { compact, flattenDeep } from "lodash/array";export const doTheMagic = master => {&nbsp; const longest = master.reduce((p, c, i, a) => (a[p].length > c.length ? p : i), 0);&nbsp; const mixed = master[longest].map((i, k) => {&nbsp; &nbsp; return master.map((o, a) => {&nbsp; &nbsp; &nbsp; if (master[a][k]) return master[a][k];&nbsp; &nbsp; });&nbsp; });&nbsp; const flaten = flattenDeep(mixed);&nbsp; return&nbsp; 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript