Split javascript array of numbers into ranges

2020-07-29 23:57发布

问题:

I have an array such as:

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

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

What is the simplest way to do this with javascript?

回答1:

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);



回答2:

You could use an interval for assigning the numbers to a specific slot.

var array = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12],
    interval = 4,
    result = array.reduce(function (r, a) {
        var slot = Math.floor((a - 1) / interval);
        (r[slot] = r[slot] || []).push(a);
        return r;
    }, []);

console.log(result);



回答3:

Simplest answer:

var numbers = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12];

var array1 = []; // range 1-4
var array2 = []; // range 5-8

for(var i=0; i< numbers.length; i++) {
    if(numbers[i]>= 1 && numbers[i] <= 4) {
        array1[i] = numbers[i]
    } else if(numbers[i]>= 5 && numbers[i] <= 8) {
        array2[i] = numbers[i]
    }
        //... continue for remaining ranges
}