Different ways to populate an array in JavaScript
Last Updated :
12 Jul, 2024
Populating an array in JavaScript means initializing it with elements. This could involve adding values manually, dynamically generating values using loops or functions, or copying elements from another array. It’s a fundamental operation for creating and manipulating arrays in JavaScript programs.
These are the following ways to populate an array:
Method 1: Using Array literal notation
In JavaScript, an array literal notation is a way of creating an array by listing its elements inside square brackets, separated by commas. Using the array literal notation is a convenient method of populating an array with initial values. You can add as many values as you want, and you can mix and match different types of values.
Syntax
const array = [item1, item2, ...];
Example: In this example, we will be adding elements in the array directly using square brackets [].
JavaScript
// Declaring and initializing arrays
let nums = [1, 2, 3, 4, 5];
let names = ["Rahul", "Raju", "Rohit", "Anurag"];
// Printing both the array
console.log("nums: ", nums);
console.log("names: ", names);
Output:
nums: [ 1, 2, 3, 4, 5 ]
names: [ 'Rahul', 'Raju', 'Rohit', 'Anurag' ]
Method 2: Using a for loop
You can use a for loop to populate an array with elements. Determine how many elements you want in the array. This could be a fixed number or a variable that’s determined at runtime. Use a for loop to iterate over the desired number of elements, adding each one to the array using the push() method.
Syntax:
const arrayNumbers = [];
for (Initialization; Condition; Increment/Decrement) {
arrayNumbers.push(items);
}
Example: In the given example, we are creating an array of even numbers from 1 to 10 using a for a loop.
JavaScript
const evenNumbers = [];
for (let i = 2; i <= 10; i += 2) {
evenNumbers.push(i);
}
console.log("Even numbers: " + evenNumbers);
OutputEven numbers: 2,4,6,8,10
Method 3: Using the fill() Method
The fill() method in JavaScript is a method that is used to populate an array with a static value. It accepts two arguments: the first argument is the value that will be used to fill the array, and the second argument is the starting index from where the filling process will start.
The fill method is useful in situations where we need to initialize an array with a default value or when we need to reset the values of an array to a specific value.
Syntax:
const zeros = new Array(size_array).fill(item);
Example: In the given example, we are creating an array of 0s of size 5 using the fill method.
JavaScript
const zeros = new Array(5).fill(0);
console.log("Zeros: " + zeros);
The from() method in JavaScript is a method of populating an array. It creates a new array instance from an array-like or iterable object. The from() method returns a new array instance that contains the elements of the original array-like or iterable object.
An array-like object is an object that has a length property and can be indexed like an array, but it may not have all the methods that an array has
Syntax:
const array_ = [some array values];
const new_array = Array.from(array_);
Example: In the given example we are creating an array from a string.
JavaScript
const str = "hello";
const chars = Array.from(str);
console.log(
"New array created using elements of str: "
+ chars
);
OutputNew array created using elements of str: h,e,l,l,o
The map() method in JavaScript is a higher-order function that is used to iterate over an array and return a new array with modified elements based on a given function. The map() method applies the callback function to each element of the array in order and creates a new array with the results. The original array is not modified.
Syntax:
const array_ = [item1, item2, ....];
const squares = numbers.map(item => item * item);
Example: In this example, we take an array and create a new array using the map() method whose elements are squares of the existing array.
JavaScript
const numbers = [1, 2, 3, 4, 5];
const squares =
numbers.map((num) => num * num);
console.log("Original Array: ", numbers);
console.log("New array created by squaring "
+ "the elements ", squares);
OutputOriginal Array: [ 1, 2, 3, 4, 5 ]
New array created by squaring the elements [ 1, 4, 9, 16, 25 ]
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array.
Syntax:
let variablename1 = [...value];
Example: In this example, we will use the spread operator for filling the array.
JavaScript
let populateArray = [...new Array(5)].map(() => 0);
console.log(populateArray);
Method 7: Using the Array.of() Method
The Array.of() method creates a new array instance with a variable number of arguments, regardless of the number or type of the arguments. It provides a way to initialize arrays without needing to specify the size or use array literals.
Exampe: Using Array.of() provides a concise and explicit way to initialize arrays with specific elements, enhancing readability and maintainability in your JavaScript codebase.
JavaScript
const integers = Array.of(1, 2, 3, 4, 5);
console.log("Array of integers: ", integers);
OutputArray of integers: [ 1, 2, 3, 4, 5 ]
Similar Reads
Different Ways to Crate an Array of Objects in JavaScript ?
Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you
3 min read
Convert an Array to JSON in JavaScript
Given a JavaScript Array and the task is to convert an array to JSON Object. Below are the approaches to convert an array to JSON using JsvaScript: Table of Content JSON.stringify() methodObject.assign() methodJSON.stringify() methodThe use of JSON is to exchange data to/from a web server. While sen
2 min read
How to Declare an Array in JavaScript ?
Array in JavaScript are used to store multiple values in a single variable. It can contain any type of data like - numbers, strings, booleans, objects, etc. There are varous ways to declare arrays in JavaScript, but the simplest and common is Array Litral Notations. Using Array Literal NotationThe b
3 min read
How to fill static values in an array in JavaScript ?
In this article, we will see the methods to fill an array with some static values. There are many ways to fill static values in an array in JavaScript such as: Using Array fill() MethodUsing for loopUsing push() methodUsing from() methodUsing spread operatorMethod 1: Array fill() Method We use the a
5 min read
Difference Between JavaScript Arrays and Objects
Below are the main differences between a JavaScript Array and Object. FeatureJavaScript ArraysJavaScript ObjectsIndex TypeNumeric indexes (0, 1, 2, ...)Named keys (strings or symbols)OrderOrdered collectionUnordered collectionUse CaseStoring lists, sequences, ordered dataStoring data with key-value
1 min read
What is the fastest way to loop through an array in JavaScript ?
The fastest way to loop through an array in JavaScript depends upon the usecases and requirements. JavaScript has a large variety of loops available for performing iterations. The following loops along with their syntax are supported by JavaScript. Table of Content for loop while loop .forEach() loo
3 min read
How to Filter an Array in JavaScript ?
The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output. Syntax const filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note:
2 min read
How to Push an Array into Object in JavaScript?
To push an array into the Object in JavaScript, we will be using the JavaScript Array push() method. First, ensure that the object contains a property to hold the array data. Then use the push function to add the new array in the object. Understanding the push() MethodThe array push() method adds on
2 min read
How to get Values from Specific Objects an Array in JavaScript ?
In JavaScript, an array is a data structure that can hold a collection of values, which can be of any data type, including numbers, strings, and objects. When an array contains objects, it is called an array of objects. Table of Content Using the forEach() methodUsing the map() methodUsing the filte
2 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive dat
3 min read