Js Refresher - Array Functions

Ashish SahuAshish Sahu
2 min read

Higher order function

  • A functions that takes another function as a parameter

  • Return a function or an array

// Sample Object
const obj = [
    {
        name:"Ashish",
        age:25
    },
    {
        name:"Sahu",
        age:23
    },
    {
        name:"Aditya",
        age:22
    }
]

forEach() - HOF for Arrays

  • Goes to each item of an array one at a time

  • Return nothing/undef

obj.forEach((item)=>{
    console.log("Foreach ",item);
})

map() - HOF for Arrays

  • Goes to each item again but this time we can also return some new values
obj3 = obj.map((item)=>{
    return {
        name: item.name.toUpperCase(),
        age: item.age+2
    };
})

filter() - HOF for Arrays

  • Filter according to a condition
const name1 = ["ashish","aditya","avinash"]
const name2 = ["shristi","ashish"]

const toAdd = name1.filter((item)=>{
    return !name2.includes(item);
})

const toRemove = name2.filter((item)=>{
    return !name1.includes(item);
})

console.log("toAdd : ",toAdd)
console.log("toRemove : ",toRemove)

reduce() - HOF for Arrays

  • Reduce an array to a single value, smaller array or something

// group an array of object
const obj1 = obj.reduce((acc,curr)=>{
    if(acc[curr.age] === undefined){
        acc[curr.age] = [curr.name];
    }else{
        acc[curr.age].push(curr.name);
    }
    return acc;
},{})

console.log(obj1)

// flatten an nested array
const arr = [1,[3,4],[4,5,6],3,7];
const newArr = arr.reduce((acc,curr)=>{
    return acc.concat(curr);
},[])

console.log(newArr)

// sum of an array using reduce
const sm = newArr.reduce((acc,curr)=>acc+curr,0)
// output - 33

find() - HOF for Arrays

  • Return the first elements that matches a condition
const numbers2 = [3, 5, 8, 10];

const firstEven = numbers2.find(function(num) {
  return num % 2 === 0;
});

console.log(firstEven);

// -- Output -- 
// 8
  • If none found returns and undefined
0
Subscribe to my newsletter

Read articles from Ashish Sahu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashish Sahu
Ashish Sahu