Loop through Array in Javascript [8 Best Ways]

Loop through Array in Javascript [8 Best Ways] - linuxnasa

In this tutorial, we will learn about 8 best ways to loop through array in Javascript. javascript iss one of the most versatile and commonly used programming language among the developers. Like any programming language, Javascript also support the data structure called array. We will learn about array creation and 8 best ways to iterate over the array in the upcoming sections of this tutorial. So, let’s get started.

 

What is Array in Javascript

In Javascript, an array is a data structure that allows us to store multiple elements in a variable. The elements stored in an array can be of any type like numbers, strings, objects or arrays itself.  Arrays are one of the most commonly used data structure as it is used to stores collection of data. The way we declare an array in Javascript is by using ‘[] (square bracket) bracket. For example, we can create an array of strings using following way.

var str_elements = ["Linux", "Nasa", "Learn"];

 

Loop through Array in Javascript [8 Best Ways]

Also Read: How to Check if a User has Sudo Rights in Linux

There are various ways to loop through an array in Javascript. We can use loop like for loop, while loop. We can also use built-in methods in Javascript like every(), map(), filter() etc to iterate an array. We will look at 8 such methods to iterate an array using different examples in the next section.

 

1. Using for loop

The very common method to loop through a given array is by using for loop. We will understand the usage of for loop using below example. In the below example, we have declared an array which stores four elements in a variable called ‘array’. We print a message on standard output using the method console.log(“<your-message>”). We have then used for loop in which we added the logic to iterate the array elements until variable ‘index’ is less than the length of array. We print each array element using console.log(array[index]) within the for loop.

array = [5, 2, 9, 8];

console.log("Print array elements using 'for loop' method")
for (index = 0; index < array.length; index++) {
console.log(array[index]);
}

OUTPUT

Print array elements using 'for loop' method
5
2
9
8

 

2. Using while loop 

We can also use while loop to iterate the elements in a given array in the similar manner like we did using for loop in previous example. In the below example, we have used while loop in which we have defined the condition to check in variable index value is less than the length of he array. We print each element from the array until the index variable value is less than the length of the array using console.log() method. Save and execute below code. It will print all the array elements on the standard output(i.e on console).

index = 0;
array = [5, 2, 9, 8];

console.log("Print array elements using 'while loop' method")
while (index < array.length) {
console.log(array[index]);
index++;
}

OUTPUT

Print array elements using 'while loop' method
5
2
9
8

 

3. Using forEach Method

In Javascript, forEach() is a built-in method which calls the provided function once for each element of an array in the order. We can use this function to iterate the given array and print each elements from the array. We will use same code as used in previous examples. In the below example, forEach function is called on the ‘array’ variable. It takes a callback function ‘getFunc’ as an argument. This function will be executed for each element in the array. The ‘getFunc’ takes two argument, ‘item’ which represent the current element in the array and ‘index’ which represent the index of the current element. We are printing the elements on the console using console.log() method.

index = 0;
array = [5, 2, 9, 8];

console.log("Print array elements using 'forEach loop' method")
array.forEach(getFunc);
function getFunc(item, index){
console.log(item);
}

OUTPUT

Print array elements using 'forEach()' method
5
2
9
8

 

Also read: Python Import Class From Another File [Step by Step guide]

 

4. Using every Method

There is another built-in method available in Javascript known as every() method that checks if all elements in an array pass a test(provided as a function). Let us understand and execute below code to understand how every() function works. In the below example, we are using every() function on the variable ‘array’. The every() function tests whether all elements in the array pass the test implemented by the provided function, ‘less_than_ten‘. We have used ‘if-else’ loop to print the message based on condition defined on if-else loop.

index = 0;
array = [5, 2, 9, 18];

const less_than_ten = x => x <10;
console.log("Print array elements using 'every() ' method")
if (array.every(less_than_ten)) {
console.log("All array elements are less than 10");
}

else {
console.log("One or more elements are less than 10");
}

OUTPUT

Print array elements using 'every()' method
One or more elements are less than 10

 

5. Using map Method

In Javascript, map() is a built-in method that applies a function over every element and then returns the new array.  In the below example, we have defined an arrow function called ‘square’ that takes a parameter ‘x’ and returns its square using the Math.pow() method. Next, we are using the map() function on the array which applies the square function to each element of the array and create a new array with the squared values. We are printing the messages on the console using last three lines of the example below.

index = 0;
array = [5, 2, 9, 18];

square = x => Math.pow(x, 2);
square_array = array.map(square);

console.log("Print square of array elements using 'Map()' method")
console.log(array);
console.log(square_array);

OUTPUT

Print square of array elements using 'Map()' method
[ 5, 2, 9, 18 ]
[ 25, 4, 81, 324 ]

 

6. Using filter Method

In Javascript, filter() is a built-in method that creates a new array with array elements that passes a test. In the below example, we have used filter() function on the ‘nums’ array. The filter() function creates a new array containing all elements that pass a test provided as a function. In our example, it uses ‘getNum()‘ function to filter out numbers that are less than or equal to 100. We have defined getNum() function which takes three parameters: ‘value’ which represent the current element being processed, ‘index‘ which represent index of the current element and ‘array’ which represent the array ‘filter’ was called upon. If the value is less than or equal to 100, it will return the value.

var nums = [40, 56, 120, 115, 32, 700];
var under100 = nums.filter(getNum);

console.log("Print Array elements under 100 using 'filter' method")
console.log(under100);

function getNum(value, index, array) {
return value <= 100;
}

OUTPUT

Print Array elements under 100 using 'filter' method
[ 40, 56, 32 ]

 

7. Using reduce Method

In Javascript, reduce() is a built-in method which runs a function on each element of an array to produce a single value. The reduce() method does not reduce the original array. In the below example, we are calculating the sum of all elements in a given array using reduce() function. The reduce() function takes a callback function  called ‘findSum’. The reduce() function iterates over each element in the ‘num’ array.

It takes four parameter: ‘total’ which represent the accumulated result of the computation, ‘value’ which represent the current element being processed, ‘index’ which represent the index of the current element and ‘array’ which represent the array ‘nums’ itself. The function adds the ‘value‘ to the ‘total’ during each iteration and returns the final accumulated result.

var nums = [40, 56, 120, 115, 32, 200];
var under100 = nums.reduce(findSum, 0);

console.log("Print sum of Array elements using 'reduce' method")
console.log("The sum is " + under100);

function findSum(total, value, index, array) {
return total + value;
}

OUTPUT

Print sum of Array elements using 'reduce' method
The sum is 563

 

8. Using some Method

In Javascript, some() is a built-in method. In the below example, we have used some() method which checks whether at least one element in the array satisfies a given condition. In our example, the condition is defined using a callback function. It checks if each element in the array is greater than 100. The result is stored in the variable ‘result’. We have used if-else loop to print the message based on the condition which checks if value of result is true or false.

var nums = [40, 56, 120, 115, 32, 200];

console.log("Print Array elements greater than 100 using 'some' method")
var result = nums.some(function(element) {
return element > 100;
});

if (result) {
console.log("One or more element(s) in the array is greater than 100");
} 

else {
console.log("No element in the array is greater than 100.");
}

OUTPUT

Print Array elements greater than 100 using 'some' method
One or more element(s) in the array is greater than 100

 

Summary

Learn more about Javasript from wikipedia.org.

Leave a Comment