HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Array Iteration

  • forEach():
  • map():
  • filter():
  • find():
  • every():
  • some():
  • reduce():

forEach():

Executes a provided function once for each array element.

Example

let arr = [1, 2, 3, 4, 5];
arr.forEach(function(element) {
    console.log(element);
});
// Output: 1, 2, 3, 4, 5


          

map():

Creates a new array populated with the results of calling a provided function on every element in the calling array.

Example

let arr = [1, 2, 3, 4, 5];
let mappedArray = arr.map(function(element) {
    return element * 2;
});
// mappedArray is [2, 4, 6, 8, 10]


          

filter():

You can use Math.min.apply to find the lowest number in an array:

Example

 Creates a new array with all elements that pass the test implemented by the provided function.

find():

Returns the value of the first element in the array that satisfies the provided testing function.

Example

let arr = [1, 2, 3, 4, 5];
let foundElement = arr.find(function(element) {
    return element > 2;
});
// foundElement is 3
 

every():

Tests whether all elements in the array pass the test implemented by the provided function.

Example

let arr = [1, 2, 3, 4, 5];
let allGreaterThanZero = arr.every(function(element) {
    return element > 0;
});
// allGreaterThanZero is true
 

some():

Tests whether at least one element in the array passes the test implemented by the provided function.

Example

let arr = [1, 2, 3, 4, 5];
let hasEven = arr.some(function(element) {
    return element % 2 === 0;
});
// hasEven is true
 

reduce():

Executes a reducer function on each member of the array, resulting in a single output value.

Example

let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce(function(accumulator, currentValue) {
    return accumulator + currentValue;
}, 0);
// sum is 15
You can click on above box to edit the code and run again.

Output