How to create an array filled with values from 0 to n in javascript?

Asked

Viewed 1,090 times

12

I need to create an array that is filled with the values of 0 a n, as if using the function range(n), Python3, but using Javascript features.

I thought I’d create a function:

function generateRange(n){
    let range = new Array(n);

    range.forEach((x, index) => {
      x = index+1;
    })

    return range;
}

But I found this way too laborious, and perhaps unnecessary. There is a simpler way to treat this data and generate the same result?

  • Arthur, this method of yours, in my opinion, is very clean, easy to understand, however much I make a different code for you, it is possible that you do not think it better than yours, so your question is based on opinion.

4 answers

9


Simpler doesn’t necessarily mean clearer, your method seems good to me, but if you want something simpler, you can use the Array., which basically returns an array and executes a map inside, which allows you to increment the values:

function generateRange(n){
   return Array.from({length: n}, (_, i) => i + 1);
}

console.log(generateRange(10));

If you wanted equal values, it would be simpler still, just use Array.Fill:

function generateRange(totalElementos, valor){
       return Array(totalElementos).fill(valor);
    }

console.log(generateRange(10, 5));

There is still a simpler way, using Array.Keys, either returns the index key, ie a numerical sequence, perhaps the simplest for what your case:

function generateRange(totalElementos){
    return Array.from(Array(totalElementos).keys());
    }

console.log(generateRange(10));

7

There’s no miracle, the only thing is that I think it’s silly to use forEach(), took fashion people do this but has zero need, is a complicator, usually leave longer and certainly slower without giving any extra readability, on the contrary, it is common for people not understand the consequences of doing this, in addition to preventing certain constructions, it’s all fashion. I would do so:

function generateRange(n) {
    let range = [];
    for (let i = 0; i <= n; i++) range[i] = i + 1;
    return range;
}
console.log(generateRange(5));

Certainly it has function that can reduce a little, if you can use something ready and modern versions of JS can use alternatives, for example:

console.log(Array.from({length: 5}, (v, k) => k + 1));

I put in the Github for future reference.

5

Javascript has no ready way to generate a populated array in a single row. Something I would like to be standard in Javascript would be a function range to generate an iterator.

If you want to implement one yourself, you could do it this way:

function* range(inicio, fim, incremento = 1) {
    if (fim === undefined) {
        [inicio, fim] = [0, inicio];
    }

    if (fim > inicio) {
        if (incremento < 0) incremento *= -1;
        for (var i = inicio; i < fim; i += incremento) {
            yield i;
        }
    } else {
        if (incremento > 0) incremento *= -1;
        for (var i = inicio; i > fim; i += incremento) {
            yield i;
        }
    }
}

// Array de 0 a 5
var arr1 = Array.from(range(5));
console.log(arr1);

// Também funciona com o operador rest 
var arr2 = [...range(5)];
console.log(arr2);

// Array de 5 a 10
var arr3 = [...range(5, 10)];
console.log(arr3);

// Array de 0 a 10 incrementando de 2 em 2
var arr4 = [...range(0, 10, 2)];
console.log(arr4);

// Array de 10 a 0 decrementando de 2 em 2
var arr5 = [...range(10, 0, -2)];
console.log(arr5);

// Também funciona como iterador
for (var i of range(3)) {
  console.log(i);
}

2

You can do this using only one line, using the methods keys() and from() of ES6, as follows:

let array = Array.from(Array(10).keys());
console.log(array);

Or using thespread operator, gets smaller even:

let array = [...Array(10).keys()];
console.log(array);

That way, the array always starts from scratch, to start from another number to your choice, you will have to pass a Mapping function:

let array = Array.from(Array(10), (e, i) => i + 1); // basta trocar o 1, pelo número que voce quer que comece o array
console.log(array);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.