【问题标题】:Split An Array into chunks in a specific order ( NO ITS NOT duplicate ) PLZ [duplicate]按特定顺序将数组拆分为块(没有重复)PLZ [重复]
【发布时间】:2021-12-30 07:21:40
【问题描述】:

我正在尝试将这个数组分成 3 个块,并且需要将每 3 个数字推入其中,有人可以帮忙吗?

//做这个:

[1, 2, 3, 4, 5, 6, 7, 8, 9];

//到这个:

[[1, 4, 7], [2, 5, 8], [3, 6, 9]];

英语不好抱歉。

【问题讨论】:

  • 即使它不是重复的:"bad English sorry." - 这不是问题,因为这里的主要问题是:bad attitude 。这不是一个“请免费为我写这篇文章”的网站,你应该总是展示你至少做了一个尝试
  • 我真的需要帮助,而且我的英语很糟糕,对此我很抱歉,没有冒犯不要误会我的意思......
  • 这里没有人被你的英语冒犯,但你在这里展示的总缺乏努力并不好。
  • 这与常规分块不同
  • 很抱歉给你那种感觉……我做了一整天,感到绝望……我对这里的文化了解不多

标签: javascript arrays chunks


【解决方案1】:

您可以通过Array.prototype.reduce() 实现这一目标

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const result = arr.reduce((array, item, index) => { 
  const chunkIdx = Math.floor(index % 3);
  if (!array[chunkIdx]) {
    array[chunkIdx] = []
  }
  array[chunkIdx].push(item)
  return array;
}, [])

console.log(result)

更多关于reduce - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

【讨论】:

    【解决方案2】:

    尝试使用reduce()

    const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    const chunk = function(array, length) {
      return array.reduce(
        (a, v, i) => (a[i % length].push(v), a), 
        Array.from({ length }, _ => [])
      )
    }
    
    console.log(chunk(array, 3))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2012-07-04
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 2016-07-03
      相关资源
      最近更新 更多