Search This Blog

2023/10/13

Javascript : Create an array with sequential integer values

For creation of an array with sequential integer values lets
consider following code

Code:
const n=10
const arr1 = Array.from(Array(n).keys());
console.log(arr1)

Output:
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
Explantion:
Lets break down statement
Array.from(Array(n).keys())
into its parts.

1) Array(n): Creates a new array with a length of n. This array initially
contains empty slots (sparse array), meaning it has n slots but no
defined elements.

2) .keys(): Accesses the keys (indices) of the array. This returns an
iterator that generates sequential integer keys starting from 0 up
to n - 1.

3) Array.from(...): Converts the iterator (keys) into an array. The
Array.from method takes an iterable or array-like object and creates a
new array from its elements or values. In this case, it converts the
iterator of keys into an array containing integers from 0 to n - 1.
Code:
const n=10
let arr2 = new Array(n).fill().map((_,index)=> index)
console.log(arr2)

Output:
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]

Explanation:
The code above creates a new array of length n, fills it with undefined
values, and then uses the map method to transform each element to its
index value.
Note:
Instead of statement
let arr2 = new Array(n).fill().map((_,index)=> index)
if we put
let arr2 = new Array(n).map((_,index)=> index)
we get output as [ <10 empty items> ].

Observation:
Consider following code.
Code:
const n=10
let iterator = Array(n).keys()
for(var m of iterator ){
console.log(m)
}
Output:
0
1
2
3
4
5
6
7
8
9
Explanation:
Array(n).keys() method to create an iterator for generating sequential
integer keys from 0 to n - 1, and then iterates through this iterator
using a for...of

No comments:

Post a Comment