将Javascript数组元素拆分为指定索引处的块 [英] Split Javascript array elements into chunks at designated indexes

查看:84
本文介绍了将Javascript数组元素拆分为指定索引处的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组

const arr = [3,6,9,12,18,21,24,27,33,36];

我想将数组 arr 分成12、21和33的块。就是索引3、5和8。我想生成另一个数组,如下所示。.

I want the array arr split into chunks at 12, 21 and 33. That is at the index 3, 5, and 8. I want to produce another array chunks looking like this..

const chunks = [[3,6,9,12],[18,21],[24,27,33],[36]];

我在这里看到的解决方案基本上将数组拆分为n个块。基本上我想在几个(指定的)索引处拆分数组。

The solutions I have seen here basically split arrays into 'n' chunks. Basically I want to split at arrays at several (specified) indexes.

我不介意underscore.js / lodash解决方案。谢谢

I do not mind an underscore.js/lodash solution. Thanks

推荐答案

您可以使用 reduceRight 并确定要拆分的元素。由于您提供的是子数组的 last 值而不是 first 的值,因此从右向左移动实际上更容易一些,因此我使用了 reduceRight 而不是 red

You could use reduceRight and decide which elements to split at. Since you’re providing the last values of a sub-array rather than the first ones, going from right to left is actually a bit easier, hence I use a reduceRight rather than a reduce.

const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
  splitValues = [12, 21, 33],
  chunks = arr.reduceRight((result, value) => {
    result[0] = result[0] || [];

    if (splitValues.includes(value)) {
      result.unshift([value]);
    } else {
      result[0].unshift(value);
    }

    return result;
  }, []);

console.log(chunks);

.as-console-wrapper { max-height: 100% !important; top: 0; }

const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
  splitIndexes = [3, 5, 8],
  chunks = arr.reduceRight((result, value, index) => {
    result[0] = result[0] || [];

    if (splitIndexes.includes(index)) {
      result.unshift([value]);
    } else {
      result[0].unshift(value);
    }

    return result;
  }, []);

console.log(chunks);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于将Javascript数组元素拆分为指定索引处的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆