JavaScript array looping

0
1711

In this article, I show you the few methods for looping over arrays in Javascript. We’ll start with the classical ones and move towards additions made to the standard.

while

let index = 0;
const array = [1,2,3,4,5,6,7,8,9];

while (index < array.length) {
  console.log(array[index]);
  index++;
}

for (classic)

const array = [1,2,3,4,5,6];
for (let index = 0; index < array.length; index++) {
  console.log(array[index]);
}

forEach

const array = [1,2,3,4,5,6];

array.forEach(function(current_value, index, array) {
  console.log(`Index if an array is ${index} and the value is ${current_value}`);
});

map

 

it’s too useful when you need to add any new element in the object. but it’s doesn’t return a new array so you need to store it again in new var or assign to the same var.
The full signature for map is .map(current_value, index, array)

const array = [1,2,3,4,5,6];
const square = x => Math.pow(x, 2);
const squares = array.map(square); //  const squares = array.map(x => Math.pow(x, 2))
console.log(`Original array: ${array}`);
console.log(`Squared array: ${squares}`);

reduce

From MDN:

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.

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}`);

filter

it’s used to filter element from an array based on boolean function

const array = [1,2,3,4,5,6];
const even = x => x % 2 === 0;
const even_array = array.filter(even); // const even_array = array.filter(x => x % 2 === 0);
console.log(`Even numbers in array ${array}: ${even_array}`);

every

 

it's used to test condition on each element of an array

const array = [1,2,3,4,5,6];
const below_seven = x => x < 7;

if (array.every(below_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');
}

some

 

it’s used to test at last one element match out condition

const array = [1,2,3,9,5,6,4];
const above_seven = x => x > 7;

if (array.some(above_seven)) {
  console.log('At least one element bigger than 7 was found');
} else {
  console.log('No element bigger than 7 was found');
}

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here