Open In App

JavaScript Array Iteration Methods

JavaScript Array iteration methods perform some operation on each element of an array. Array iteration means accessing each element of an array.

There are some examples of Array iteration methods are given below:



Method 1: Using Array forEach() Method

The array.forEach() method calls the provided function (a callback function) once for each element of the array. The provided function is user-defined, it can perform any kind of operation on an array.

Syntax:  



array.forEach(function callback(value, index, array) {
} [ThisArgument]);

Parameters: This function accepts three parameters as mentioned above and described below:  

Example: This example uses the forEach() method on an array for iterating every element of an array and printing every element of an array in a new line.




let emptytxt = "";
let  Arr = [23, 212, 9, 628, 22314];
 
function itrtFunction(value, index, array) {
    console.log(value);
}
 
Arr.forEach(itrtFunction);

Output
23
212
9
628
22314


Method 2: Using Array some() Method

The array.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument function.

Syntax:  

array.some(arg_function(value, index, array), thisArg);

Parameters: This method accepts three parameters as mentioned above and described below:  

Example: This example checks all value of the array, if some value is greater than 50 then it returns true and if all elements of an array are less than 18 then it returns false.




let Arr1 = [41, 2, 54, 29, 49];
let someOver50 = Arr1.some(myFunction1);
 
console.log("Are some values over 50: "
            + someOver50);
 
function myFunction1(value, index, array) {
    return value > 50;
}
 
let Arr2 = [41, 2, 14, 29, 49];
let allLessThan18 = Arr2.some(myFunction2);
 
console.log("Are all values less than 18: "
            + allLessThan18);
 
function myFunction2(value, index, array) {
    return value < 18;
}

Output
Are some values over 50: true
Are all values less than 18: true


Method 3: Using Array map() Method

The array.map() method creates an array by calling a specific function on each item in the parent array and it does not change the value or element of the array.

Syntax:  

array.map(function(value, index, array){
}[ThisArgument]);

Parameters: This method accepts three parameters as mentioned above and described below: 

Example: This example performs a sum operation on every element of the array and displays output. It does not change the values of the original array.




let numArray = [1, 2, 3, 4];
let numArray2 = numArray.map(multiplyFunction);
 
console.log(numArray2);
 
function multiplyFunction(value, index, array) {
    return value + 100;
}

Output
[ 101, 102, 103, 104 ]


Similar Articles 

All these are the array iterator functions.


Article Tags :