title: Create array sequence [0, 1, ..., N-1]
in one line
tip-number: 33
tip-username: SarjuHansaliya
tip-username-profile: https://github.com/SarjuHansaliya
tip-tldr: Compact one-liners that generate ordinal sequence arrays
- /en/create-range-0...n-easily-using-one-line/
Here are two compact code sequences to generate the N
-element array [0, 1, ..., N-1]
:
Array.apply(null, { length: N }).map(Function.call, Number);
Array.apply(null, {length: N})
returns anN
-element array filled withundefined
(i.e.A = [undefined, undefined, ...]
).A.map(Function.call, Number)
returns anN
-element array, whose indexI
gets the result ofFunction.call.call(Number, undefined, I, A)
Function.call.call(Number, undefined, I, A)
collapses intoNumber(I)
, which is naturallyI
.- Result:
[0, 1, ..., N-1]
.
For a more thorough explanation, go here.
It uses Array.from
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from
Array.from(new Array(N), (val, index) => index);
Array.from(Array(N).keys());
A = new Array(N)
returns an array withN
holes (i.e.A = [,,,...]
, butA[x] = undefined
forx
in0...N-1
).F = (val,index)=>index
is simplyfunction F (val, index) { return index; }
Array.from(A, F)
returns anN
-element array, whose indexI
gets the results ofF(A[I], I)
, which is simplyI
.- Result:
[0, 1, ..., N-1]
.
If you actually want the sequence [1, 2, ..., N], Solution 1 becomes:
Array.apply(null, { length: N }).map(function (value, index) {
return index + 1;
});
and Solution 2:
Array.from(new Array(N), (val, index) => index + 1);