DEV Community

Cover image for The 8 must know JavaScript looping array function
Prima Tondy Arya Kurniawan
Prima Tondy Arya Kurniawan

Posted on

The 8 must know JavaScript looping array function

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]
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
orime112 profile image
Orime

Array.entries

let arr = [1, 2, 3]
let entriesLoop = arr.entries()
entriesLoop.next() // {value: [0, 1], done: false}
entriesLoop.next() // {value: [1, 2], done: false}
entriesLoop.next() // {value: [2, 3], done: false}
entriesLoop.next() // {value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
primakurniawan profile image
Prima Tondy Arya Kurniawan

do you find another must know JavaScript looping method