Here is Your Complete Guide about JS Array : part -4:- Map, Reduce and filter

Here is Your Complete Guide about JS Array : part -4:- Map, Reduce and filter

Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. Each method do iteration through each element of the array based on the function and return each of the output and add it into new array at the end of iterations. These are faster than for loops. In this article, you will learn why and how to use each one.

the map method

const arr  = [1,2,3];
const arrNew = arr.map(value=>value*2);
console.log(arrNew)    //output:- [2,4,6]
console.log(arr)   //output:- [1,2,3]

but Krishna, it looks similar to .forEach() method. is it? let's see

const arr = [1,2,3];
arr.forEach(value => console.log(value*2));         
//output:- 2
                  4
                  6

so map method returns a brand new array on the console. It does not return element one by one, instead return each of the output and add it into new array. while in forEach, we performed some action that is visible on the console in each iteration.

theReduce method

It is mainly use to find sum, max, min or avg of all elements of array

syntax - arr.reduce(function(accumulator/initializer, value,index){ return .......}, starting value of accumulator/initializer)

// find sum of all elements of arr
const arr = [1,2,3,4];
const sum = arr.reduce(function(acc,value){
                                                                    reutrn acc + value;}, 100);
console.log(sum)  // output:- 100+1+2+3+4 = 110

find min of all elements of an array

const arr = [1,2,3,4,5];
const min = arr.reduce(function(initializer,value){
                                                            return value<initializer ? value : initializer};)

if 2nd argument of reduce() is not given, acc/init = arr[0] & current-value = arr[1] if 2nd arg of reduce() is given, acc/init=given value & current-value = arr[0]

The filter method

if filters out element of array based on some conditions.

const arr = [1,2,3,4,5]
const oddArr = arr.filter(val=>val%2 !== 0)
console.log(oldArr)    //output:- [1,3,5]

some()

return T is one or more element of the array met the defined condition else return F

every()

it is same as some() but only returns T if all element of array met the condition else return F.

flat()

it is added in ES2019. It is used to flatten 2-D arrays.

it do flattening at 1st level only, not at 2nd level of nesting

sort()

works well for strings sorting. it mutates origina larray

const arr =Array.from('krishna')
console.log(arr.sort());    //output:- Array(7) [ "a", "h", "i", "k", "n", "r", "s" ]

it does not work well for numbers.

const arr = [1,7,2,3,9];
consolr.log(arr.sort((a,b)=>a-b);    //output:- [1,2,3,7,9]

.indexOf()

return index of value in the array. if value is not present, return -1.

.reverse()

it reverse order of elements of array

.includes()

return T if array contains the given value else returns false

Most recent updates

.at(index)

return element at the given index. This is not to suggest there is anything wrong with using the square bracket notation. For example array[0] would return the first item. However instead of using array.length for latter items; e.g. array[array.length-1] for the last item, you can call array.at(-1)

findIndex()

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. syntax- arr.findIndex((element, index, array) => { // } )

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));  // expected output: 3

create m * n array

const matrix = Array.from(Array(m),()=>Array(n)) 
const matrix = Array(m).map(()=>Array(n));

Array Destructuring

const arr = [2,3,4];
const [x,y,z] = arr;   /// destructuring x=2,y=3,z=4
const [a,,b] = arr;    // destructuring  a= 2, b=4

we can use destructing in switching values of variables too;

a= 5; 
b= 6;
[a,b] = [b,a];  // now a= 6, b=5

spread operator on array

it helps in creating new array based on given array but with new elements at the beginning

const arr = [2,3,4];
const newArr = [1,2,...arr];   //output:- newArr= [1,2,2,3,4]

spread operator also helps in creating shallow copy of an array

const arr1 = [1,2,3];
const arr2 = [...arr1];   ///creates shallow copy of arr1

Read more about other part of this series:-

  1. krishnasaini.hashnode.dev/here-is-your-comp..
  2. krishnasaini.hashnode.dev/here-is-your-comp..
  3. krishnasaini.hashnode.dev/here-is-your-comp..