There are several ways to iterate over arrays in Javascript. We’ll start with the classics and work our way up to the standard
while
const array = [1.2.3.4.5.6];
let index = 0;
let { length } = array
while (index < length) {
console.log(array[index]);
index++;
}
Copy the code
for (classical)
const array = [1.2.3.4.5.6];
for (let index = 0; index < array.length; index++){
console.log(array[index]);
}
Copy the code
forEach
const array = [1.2.3.4.5.6];
array.forEach((current_value, index, array) = > {
console.log(`At index ${index} in array ${array} the value is ${current_value}`);
})
Copy the code
map
The last construct was useful, however, It doesn’t return a new array which might be undesirable for your specific case. Map solves this by saving a function over every element and then returning the new array.
This last construct is useful, but it does not return a new array, which may not be desirable in your particular case. Map solves this problem by applying a function to each element and then returning a new array.
const array = [1.2.3.4.5.6];
const square = x= > Math.pow(x, 2);
const squares = array.map(square);
console.log(`Original array: ${array}`);
console.log(`Squared array: ${squares}`);
Copy the code
reduce
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
The reduce() method applies a function to each element (left to right) in the accumulator and array to reduce it to a single value.
const array = [1.2.3.4.5.6];
const sum = (x, y) = > x + y;
const array_sum = array.reduce(sum, 0);
console.log(`The sum of array: ${array} is ${array_sum}`);
Copy the code
filter
Filters elements on an array based on a boolean function.
Filters the elements of an array based on Boolean functions.
const array = [1.2.3.4.5.6];
const even = x= > x % 2= = =0;
const even_array = array.filter(even);
console.log(`Even numbers in array ${array}: ${even_array}`);
Copy the code
every
Got an array and want to test if a given condition is met in every element?
Given an array, you want to test whether a given condition is met in each element?
const array = [1.2.3.4.5.6];
const under_seven = x= > x < 7;
if (array.every(under_seven)) {
console.log('Every element in the array is less than 7');
} else {
console.log('At least one element in the array was bigger than 7');
}
Copy the code
some
Test if at least one element matches our boolean function.
Tests whether at least one element conforms to our Boolean function.
const array = [1.2.3.9.5.6.4];
const over_seven = x= > x > 7;
if (array.some(over_seven)) {
console.log('At least one element bigger than 7 was found');
} else {
console.log('No element bigger than 7 was found');
}
Copy the code