繁体   English   中英

如果满足特定条件,则生成新数组(Javascript)

[英]Generating a new array if a certain criteria is met (Javascript)

我有一个用户数组,所有这些用户都需要添加到组数组中。 如果组数组少于3个用户,我想将用户添加到该组数组。 如果组阵列已经有3个用户,我想将当前的组阵列推到另一个收集所有组的阵列,并为接下来的3个用户启动另一个新的组阵列,直到没有用户为止。


错误-

let group[i] = [];

Unexpected token [


我一直在绞尽脑汁试图解决这个问题。 也许盯着屏幕看了太久。

这是我一直尝试的不同版本,但控制台没有给我留下深刻的印象-

function createGroups(totalPeople){
  let i = 1
  let group[i] = [];
  let array = totalPeople

  totalPeople.map((user) => {

    if(group[i] =< 3){
      group[i].push(user)
    }else{
      array.push(group[i]);
      i++
    }
  })
};

totalPeople是在我的代码的前面创建的数组,这是文件中唯一未按预期运行的部分。 任何有关如何执行此操作的方法的帮助或有关修复此代码的建议都将大有帮助! 谢谢!

尝试将组初始化为数组:

let i = 1
  let group = [] // Initialize as an array
   group[i] = [];
  let array = totalPeople

  totalPeople.map((user) => {

    if(group[i] =< 3){
      group[i].push(user)
    }else{
      array.push(group[i]);
      i++
    }
  })

您的代码中存在一些问题:

function createGroups(totalPeople){
  let i = 1
  let group[i] = []; // issue #1
  let array = totalPeople

  totalPeople.map((user) => {

    if(group[i] =< 3){ // issues #2 and #3 
      group[i].push(user)
    }else{
      array.push(group[i]); // issue #4 
      i++; // issue #5 
    }
  })
};

问题1:

您需要在添加索引之前将group定义为数组。

let group = []; 
group[i] = [];

问题2:

看起来您是要比较group[i].length和3

问题3:

使用<=代替=<来比较您的数字。 另外,如果将长度与<= 3进行比较,则每个组将有4个人。 因为数组中的第一个索引为0。

问题4:

您正在推向array ,这是对totalPeople的引用。 这是你的意思吗? 因为我怀疑它会产生预期的结果。 您可能需要初始化一个空数组,然后将group [i]数组推入其中。 然后,返回该新数组。 在函数式编程中,返回一个新数组而不修改作为参数传递的数组通常是一个好习惯。

问题5:

如果增加i ,则需要将group[i]初始化为数组,否则在下一次循环迭代时将无法将其推入。

差异逻辑:

现在,您已经解决了代码中的问题,下面的代码片段显示了使用Array.prototype.reduce的另一种方法:

 const totalPeople = ["Joe", "Jack", "Jerry", "Jane", "Mary", "Billy", "Vicky", "Bobby"]; const groupsOfThree = totalPeople.reduce((accumulator, currentPerson, index) => { // pushing the current person in the topest group in the accumulator accumulator[accumulator.length-1].push(currentPerson); // if it's the 3rd person, we're pushing the an empty group in the accumulator if (index % 3 === 2) { accumulator.push([]); } return accumulator; }, [[]]); // the initial value of the accumulator will be an array containing an empty group console.log(groupsOfThree); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM