首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Javascript中通过中断将数组拆分为块

在Javascript中通过中断将数组拆分为块
EN

Stack Overflow用户
提问于 2018-08-09 02:45:11
回答 2查看 140关注 0票数 0

在javascript中,如何通过中断将数组拆分成块?例如,

var array = [0,1,2,3,4,5,6,7,8,9,12,13,15,20]
var breaks = [0,3.5,13]
somefunction(array, breaks) === [[0,1,2,3],[4,5,6,7,8,9,12],[13,15,20]]
// true

中断中的值不一定在数组中。

EN

回答 2

Stack Overflow用户

发布于 2018-08-09 02:55:04

您可以对break数组使用索引,并在迭代array时检查该值。对于每个找到的值,添加一个新数组。

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 15, 20],
    breaks = [0, 3.5, 13],
    index = 0,
    result = array.reduce((r, v) => {
        if (v >= breaks[index]) {
            r.push([]);
            ++index;
        }
        r[r.length - 1].push(v);
        return r;
    }, []);

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

票数 0
EN

Stack Overflow用户

发布于 2018-08-09 03:24:02

reduce的另一个版本,使用它的可选参数

breaks.reduce((acc, cur, idx, arr) => {
  acc.push(
    array.slice(
      array.indexOf(cur),
      arr[idx+1] ? array.indexOf(arr[idx+1]) : array.length
    )
  );
  return acc;
}, [])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51753672

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档