- Create array using for loop in javascript
- # Using the Array.from() method instead
- # Create an Array of N non-primitive elements with the same value
- # Creating a two-dimensional array with N elements, same value
- # Repeating multiple values N times
- # Create an Array with N elements, same Value using a for loop
- # Create an Array with N elements, same Value using a while loop
- # Additional Resources
- Create Array from 1 to 100 in JavaScript
- Use Array.from() with Array.keys()
- Create array using for loop in javascript
- # Using the Array.from() method instead
- # Create an Array of N non-primitive elements with the same value
- # Creating a two-dimensional array with N elements, same value
- # Repeating multiple values N times
- # Create an Array with N elements, same Value using a for loop
- # Create an Array with N elements, same Value using a while loop
- # Additional Resources
Create array using for loop in javascript
We used the Array.fill method to fill the array with a specific value.
Copied!// ποΈ [ 'abc', 'abc', 'abc' ] console.log(Array(3).fill('abc'));
The method takes a value and uses it to replace all array elements.
# Using the Array.from() method instead
Alternatively, you can use the Array.from() method instead of the Array() constructor.
Copied!const arr = Array.from(length: 3>).fill('a'); console.log(arr); // ποΈ ['a', 'a', 'a']
We passed the desired array length as an argument to the Array.from method.
Using the Array.from method is a little more explicit and easier to read than instantiating the Array constructor.
# Create an Array of N non-primitive elements with the same value
When creating an array of N non-primitive elements with the same value, use the Array.from() method.
Copied!const arr = Array.from(length: 3>, () => return name: 'Bobby Hadz'>; >); // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ] console.log(arr);
Creating an array of non-primitive values is a bit trickier because we have to ensure that the objects in the array don’t have the same reference.
If the objects are stored at the same location in memory, once one object gets updated, they all get updated.
Instead, we passed a map() function as the second argument to the Array.from() method.
On each call of the map function, we return an object.
If you update one object, the changes won’t be reflected in the object objects because they are all stored in different locations in memory.
Copied!const arr = Array.from(length: 3>, () => return name: 'Bobby Hadz'>; >); // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ] console.log(arr); arr[0].name = 'new'; // [ < name: 'new' >, < name: 'Bobby Hadz' >, < name: 'Bobby Hadz' >] console.log(arr);
Updating the name property of the first object didn’t update the property in the other objects.
# Creating a two-dimensional array with N elements, same value
The same approach can be used to create a two-dimensional array with N elements, same value.
Copied!const arr = Array.from(length: 2>, () => Array.from(length: 3>, () => return name: 'Bobby Hadz'>; >), ); // [ // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ], // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ] // ] console.log(arr);
Notice that we used the Array.from() method twice.
The outer call to the Array.from() method determines the length of the outer array.
The nested call to Array.from() determines the length of each nested array.
# Repeating multiple values N times
You can use the same approach if you need to create an array by repeating multiple values N times.
Copied!const arr = Array(3).fill(['a', 'b', 'c']).flat(); // [ // 'a', 'b', 'c', // 'a', 'b', 'c', // 'a', 'b', 'c' // ] console.log(arr);
We passed an array of values to the Array.fill() method and use the Array.flat() method to flatten the array.
You can also pass a map function as the second argument to the Array.from() method when working with primitives.
Copied!const arr = Array.from(length: 5>, () => return 'a'; >); // ποΈ [ 'a', 'a', 'a', 'a', 'a' ] console.log(arr);
The code sample creates an array of 5 elements with the value of a .
You can also explicitly chain a call to the Array.map() function on the output of the Array.from() method.
Copied!const arr = Array.from(Array(5)).map(() => return 'a'; >); // ποΈ [ 'a', 'a', 'a', 'a', 'a' ] console.log(arr);
The Array.map() function gets called for each element in the array.
Alternatively, you can use a for loop.
# Create an Array with N elements, same Value using a for loop
This is a three-step process:
- Declare a variable that stores an empty array.
- Use a for loop to iterate N times.
- On each iteration, push the value into the array.
Copied!const arr = []; const total = 3; for (let i = 0; i total; i++) arr.push('a'); > console.log(arr); // ποΈ ['a', 'a', 'a']
We declared a new arr variable and initialized it to an empty array.
We used a for loop to iterate N times and on each iteration, we pushed the value into the new array.
Using a for loop is a bit more verbose, but many developers are familiar with how loops work.
# Create an Array with N elements, same Value using a while loop
You can also use a while loop to create an array of N elements with the same value.
Copied!let total = 3; const arr = []; while (total--) arr.push('a'); > console.log(arr); // ποΈ [ 'a', 'a', 'a' ]
On each iteration of the while loop, we decrement the total variable until it gets set to 0 .
Zero is a falsy value in JavaScript, so once 0 is reached, the loop exits.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Create Array from 1 to 100 in JavaScript
Using loops is useful when we are supposed to perform the same function repeatedly. For example, we used a for loop because we wanted to insert a value into an array often; this value can be the same or different, and we are inserting a different value in each iteration.
The third expression, i++ , is used to increment the value of i . Finally, inside the for loop, we used the push() method, which can add a new item to an end of the array, changes the arrayβs length and returns the new size/length of the array.
Finally, we used the console.log() method to display the array values on the console. In JavaScript, we have to be careful about the following points while using a for loop:
- The first expression is optional, and we can omit it. In that case, we can initialize the variableβs value before writing the loop. Note that we can initialize multiple variables in the first expression; this case would be helpful if we have to create two arrays, one from 1 to 100 and the second from 101 to 200 using one for loop.
- The second expression is optional, and we can omit that. Remember, if we donβt want to have the second expression, we must write a break inside the for loop; otherwise, it would be a never-ending loop and crash the browser.
- The third expression can also be omitted, and we can increment the variableβs value inside the for loop.
You may have noticed that using the for loop requires more lines of code and care. What if we can have some shorter ways of achieving the same results? Letβs explore them below.
Use Array.from() with Array.keys()
If we are using ES6 (ECMAScript6), then we can use this approach to create the array from 1 to 100 in JavaScript:
- Use the Array() constructor to instantiate the Array class or we can say to create an Array object.
- Pass an integer ranging from 0 to 2^(32 — 1) (inclusive) to the Array() constructor. It will create a new array with a length property set to the number we passed in Array() .
- Use the .keys() method to get an Array Iterator Object with the arrayβs keys.
- Use the .from() method to get an array from an iterable object that we get using the .keys() method in the previous step.
- Use the .slice() method to specify the start position.
Create array using for loop in javascript
We used the Array.fill method to fill the array with a specific value.
Copied!// ποΈ [ 'abc', 'abc', 'abc' ] console.log(Array(3).fill('abc'));
The method takes a value and uses it to replace all array elements.
# Using the Array.from() method instead
Alternatively, you can use the Array.from() method instead of the Array() constructor.
Copied!const arr = Array.from(length: 3>).fill('a'); console.log(arr); // ποΈ ['a', 'a', 'a']
We passed the desired array length as an argument to the Array.from method.
Using the Array.from method is a little more explicit and easier to read than instantiating the Array constructor.
# Create an Array of N non-primitive elements with the same value
When creating an array of N non-primitive elements with the same value, use the Array.from() method.
Copied!const arr = Array.from(length: 3>, () => return name: 'Bobby Hadz'>; >); // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ] console.log(arr);
Creating an array of non-primitive values is a bit trickier because we have to ensure that the objects in the array don’t have the same reference.
If the objects are stored at the same location in memory, once one object gets updated, they all get updated.
Instead, we passed a map() function as the second argument to the Array.from() method.
On each call of the map function, we return an object.
If you update one object, the changes won’t be reflected in the object objects because they are all stored in different locations in memory.
Copied!const arr = Array.from(length: 3>, () => return name: 'Bobby Hadz'>; >); // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ] console.log(arr); arr[0].name = 'new'; // [ < name: 'new' >, < name: 'Bobby Hadz' >, < name: 'Bobby Hadz' >] console.log(arr);
Updating the name property of the first object didn’t update the property in the other objects.
# Creating a two-dimensional array with N elements, same value
The same approach can be used to create a two-dimensional array with N elements, same value.
Copied!const arr = Array.from(length: 2>, () => Array.from(length: 3>, () => return name: 'Bobby Hadz'>; >), ); // [ // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ], // [ // < name: 'Bobby Hadz' >, // < name: 'Bobby Hadz' >, // // ] // ] console.log(arr);
Notice that we used the Array.from() method twice.
The outer call to the Array.from() method determines the length of the outer array.
The nested call to Array.from() determines the length of each nested array.
# Repeating multiple values N times
You can use the same approach if you need to create an array by repeating multiple values N times.
Copied!const arr = Array(3).fill(['a', 'b', 'c']).flat(); // [ // 'a', 'b', 'c', // 'a', 'b', 'c', // 'a', 'b', 'c' // ] console.log(arr);
We passed an array of values to the Array.fill() method and use the Array.flat() method to flatten the array.
You can also pass a map function as the second argument to the Array.from() method when working with primitives.
Copied!const arr = Array.from(length: 5>, () => return 'a'; >); // ποΈ [ 'a', 'a', 'a', 'a', 'a' ] console.log(arr);
The code sample creates an array of 5 elements with the value of a .
You can also explicitly chain a call to the Array.map() function on the output of the Array.from() method.
Copied!const arr = Array.from(Array(5)).map(() => return 'a'; >); // ποΈ [ 'a', 'a', 'a', 'a', 'a' ] console.log(arr);
The Array.map() function gets called for each element in the array.
Alternatively, you can use a for loop.
# Create an Array with N elements, same Value using a for loop
This is a three-step process:
- Declare a variable that stores an empty array.
- Use a for loop to iterate N times.
- On each iteration, push the value into the array.
Copied!const arr = []; const total = 3; for (let i = 0; i total; i++) arr.push('a'); > console.log(arr); // ποΈ ['a', 'a', 'a']
We declared a new arr variable and initialized it to an empty array.
We used a for loop to iterate N times and on each iteration, we pushed the value into the new array.
Using a for loop is a bit more verbose, but many developers are familiar with how loops work.
# Create an Array with N elements, same Value using a while loop
You can also use a while loop to create an array of N elements with the same value.
Copied!let total = 3; const arr = []; while (total--) arr.push('a'); > console.log(arr); // ποΈ [ 'a', 'a', 'a' ]
On each iteration of the while loop, we decrement the total variable until it gets set to 0 .
Zero is a falsy value in JavaScript, so once 0 is reached, the loop exits.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.