Ways of iterating over a array in JavaScript.
Arrays in Javascripts, are single variables used to store different kind of elements.
For example, a simple array accesses may something like this:
Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!
array = [ 'geeks', '4', 'geeks' ];
// Accessing array elements one by one
console.log[array[0]];
console.log[array[1]];
console.log[array[2]];
|
Output:
There are multiple ways one can iterate over an array in Javascript. The most useful ones are mentioned below.
Using for loop.
This is similar to for loops in other languages like C/C++, Java, etc
array = [ 1, 2, 3, 4, 5, 6 ];
for [index = 0; index < array.length; index++] {
console.log[array[index]];
}
|
Output:
Using while loop.
This is again similar to other languages.
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
while [index < array.length] {
console.log[array[index]];
index++;
}
|
Output:
using forEach method.
The forEach method calls the provided function once for every array element in the order.
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
array.forEach[myFunction];
function myFunction[item, index]
{
console.log[item];
}
|
Output:
1 2 3 4 5 6
Using every method.
The every[] method checks if all elements in an array pass a test [provided as a function].
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
const under_five = x => x < 5;
if [array.every[under_five]] {
console.log['All are less than 5'];
}
else {
console.log['At least one element is not less than 5'];
}
|
Output:
Using map.
A map applies a function over every element and then returns the new array.
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
square = x => Math.pow[x, 2];
squares = array.map[square];
console.log[array];
console.log[squares];
|
Output:
Using Filter
It is used to filter values from an array and return the new filtered array
array = [ 1, 2, 3, 4, 5, 6 ];
even = x => x%2 === 0;
evens = array.filter[even];
console.log[array];
console.log[evens];
|
Output:
[ 1, 2, 3, 4, 5, 6 ] [ 2, 4, 6 ]Using Reduce
It is used to reduce the array into one single value using some functional logic
array = [ 1, 2, 3, 4, 5, 6 ];
const helperSum = [acc,curr] => acc+curr
sum = array.reduce[helperSum, 0];
console.log[array]
console.log[sum];
|
Output:
[ 1, 2, 3, 4, 5, 6 ] 21Using Some
It is used to check whether some array values passes a test
array = [ 1, 2, 3, 4, 5, 6 ];
const lessthanFourCheck = [element] => element < 4 ;
const lessthanFour = array.some[lessthanFourCheck]
console.log[array];
if[lessthanFour]{
console.log["At least one element is less than 4" ]
}else{
console.log["All elements are greater than 4 "]
}
|
Output :
[ 1, 2, 3, 4, 5, 6 ] At least one element is less than 4