2

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?

3
  • Define "simplest." Simple to read and understand? Least amount of code? Something else? Commented Feb 7, 2017 at 20:24
  • what is the type of those ranges ? Strings, numbers? Show the expected result Commented Feb 7, 2017 at 20:25
  • Most readable/efficient in the least amount of lines. Commented Feb 7, 2017 at 20:25

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

@codesmarter, the interval is from the first (and for all other) range 1-4 four. this value is used to calculate the interval of a given number for adding to the array.
3

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.