The 8 must know JavaScript looping array function
Prima Tondy Arya Kurniawan
Posted on March 2, 2021
Array.map()
Iterate through the array and returning a new value
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Array.forEach()
Iterate through the array
const array1 = ['a', 'b', 'c'];
array1.forEach(e=> console.log(e));
// expected output: "a"
// expected output: "b"
// expected output: "c"
Array.every()
Iterate through the array and check every element, return true if every element is right and false if it's not
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(e => e < 40));
// expected output: true
Array.some()
Iterate through the array and return true if there is one element is right and false if it's not
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.some(e => e < 10));
// expected output: true
Array.find()
Iterate through the array and return the first element if it's true and undefine if there is no the right element
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(e=> e> 10);
console.log(found);
// expected output: 12
Array.findIndex()
Iterate through the array and return the index of first element if it's true and -1 if there is no the right element
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(e=> e> 10);
console.log(found);
// expected output: 1
Array.sort()
Sort and array through every element, return a ascending order array if the result is greater then 0 and descending if the result is lesser then 0;
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [1, 2, 3, 4, 5]
Array.reduce()
A reducer function on each element of the array, resulting in single output value.
const array1 = [1, 2, 3, 4];
// 1 + 2 + 3 + 4
console.log(array1.reduce((accumulator, currentValue) => accumulator + currentValue));
// expected output: 10
Posted on March 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.