将数字的javascript数组拆分为范围 [英] Split javascript array of numbers into ranges

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

问题描述

我有一个数组,例如:

[16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12]

我想根据范围分为6个不同的数组1-4、5-8、9-12、13-16、17-20、21-24。

That I would like split into 6 different arrays based on ranges 1-4, 5-8, 9-12, 13-16, 17-20, 21-24.

使用javascript做到这一点的最简单方法是什么?

What is the simplest way to do this with javascript?

推荐答案

使用 Array.prototype.filter()函数的解决方案:

The solution using Array.prototype.filter() function:

var list = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12], i
    result = [];
// considering ranges `1-4, 5-8, 9-12, 13-16, 17-20, 21-24`
for (i = 1; i < 24; i+= 4) {
  result.push(list.filter(function(d){
    return ((i+4 > d) && d >= i);  // check if the number between lower and upper bound
  }));
}

console.log(result);

这篇关于将数字的javascript数组拆分为范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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