【问题标题】:Mixing Arrays using JavaScript使用 JavaScript 混合数组
【发布时间】:2020-03-11 14:09:37
【问题描述】:

像下图那样混合多个数组的最佳方法是什么,

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

【问题讨论】:

  • 所以数组是随机排列的?
  • 不是字面上随机的我希望主数组具有每个数组的第一个元素,然后是第二个,然后是第三个,等等
  • 您应该与我们分享您的解决方案
  • 仅供参考:代码照片没用,请展示您的解决方案
  • @geeksamu 在您的问题中发布您的尝试,而不是作为答案...

标签: javascript algorithm


【解决方案1】:

您可以使用 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/lodash@4.17.15/lodash.min.js"></script>

适用于不同长度的数组,并利用函数式编程来编写优雅的代码。

这是一个要运行的代码笔:https://codepen.io/matteodem/pen/mddQrwe

【讨论】:

  • 很好,我不知道 Lodash 有 zip ?️。感谢您的回答
  • ... 或者你可以只写 4 行代码并避免加载库:)
  • 我只是喜欢使用 lodash。当然会有一些开销,但这是由 OP 决定的。
  • @JeremyThille 用 Lodash 没关系,我现在的项目用的太多了
  • 如果您认为我的回答有帮助,请将其标记为已批准 :)
【解决方案2】:

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

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】:

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

【讨论】:

    【解决方案4】:

    这适用于未知数量的数组,每个数组的长度未知:

    const arrays = [
      [1, 2, 3, 4],
      ["a", "b", "c", "d", "e"],
      ["@", "#", "?"]
    ];
    
    let output = [];
    
    while (arrays.some(a => a.length)) { // While any of the arrays still has an element in it, keep going
      for (let a of arrays) {
        if (!a.length) continue;
        output.push(a.shift()); // remove the first element of the array and add it to output
      }
    }
    
    console.log(output)

    【讨论】:

    • 只是好奇,是shift() O(1)?
    • 对不起,我不明白你的问题
    • 这意味着无论输入大小如何,移位操作都在恒定时间内工作?
    • 提到转移的时间复杂度here.
    【解决方案5】:

    这是我实现这一目标的方法,一个for loop 可以做到。如果您也不知道数组的数量和数组长度,这将起作用。

    function doTheMagic(arr){
      let ans = [];
      let maxLength = -1;
      
      arr.forEach((tempArr)=>{
        if(tempArr.length > maxLength){
          maxLength = tempArr.length;
        }
      })
      
      let l1=0,l2=0,l3=0;
      
      for(let i=0;i<maxLength;i++){
        arr.forEach((tempArr)=>{
          if(tempArr[i]){
            ans.push(tempArr[i]);
          }
        })
    
      }
      return ans;
    }
    
    
    let a1 = [1,2,3,4,5];
    let a2 = ["?","?","?","?","?","?"];
    let a3 = ['1','2','3','4','5'];
    
    
    console.log(doTheMagic([a1,a2,a3]));

    【讨论】:

    • 不知道数组个数怎么办?
    • 你能检查一下我刚刚发布的我自己的解决方案吗
    • @geeksamu 我已根据您的要求更新了我的答案,希望对您有所帮助。
    【解决方案6】:

    不确定这是否更好,但是如何编写代码来处理传入的任意数量的数组。

    const weave = (...args) =>  // convert arguments to an array
      args.reduce((res, arr, offset) => {  // loop over the arrays 
        arr.forEach((v, i) => res[offset + i * args.length] = v) // loop over array and add items to their indexes
        return res
      }, []).filter(x => x !== undefined) // remove the unused indexes
    
    
    const one = [1, 2, 3]
    const two = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    const three = ['w', 'x', 'y', 'z']
    const result = weave(one, two, three)
    console.log(result)
    
    const result2 = weave(one, two)
    console.log(result2)
    
    const result3 = weave(one, two, three, ['*', '&'])
    console.log(result3)

    【讨论】:

      猜你喜欢
      • 2019-10-17
      • 2020-01-28
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多