Top Array Functions every JS developer should know!

Top Array Functions every JS developer should know!

·

2 min read

What is an array?

An array is the collection of the same data type items or elements in continuous memory allocations. Let's suppose in a class, many students are sitting in a column. They form an array of students😎. Ya cool right. I know its very basic and you all know this. Lets directly dive into some of its function every developer like you should definitely know.

What are those important functions 🤔

Map()

This method creates a new array from calling a function for every array element. This is used to just get each item of the array. This is the most useful and frequently used one.

let nameOfArray=[ “codedamn”,”mehul ”, “mohan” ].map(item=>item.length);
Console.log(nameOfArray);
//output 
8,5,5

find()

If you have an array with objects and want to find an object with specific condition they you can use find() method. Its very easy to use and understand too🤩

let nameOfArray=[
   {
id:1,
name:”codedamn”
},
{id:2,
name:”mehul”
},
{
id:3,
name: “mohan”
    }
 ];

let nameOfArray=nameOfArray.find(item=>item.id==1);
Console.log(nameofarray.name);
//output
Codedamn

filter()

This method filters down the elements from the given array that returns true for the given test provided by the function .

This method searches for the first elemnt that makes the function return true . Example let nameOfArray=[{id:1, name:”codedamn” }, {id:2, name:”mehul” }; {id:3, name: “mohan” } ]; let filteredArray=nameOfArray.filter(item=>item.id<3); Console.log(filteredArray.length); // output 2

Concat()

The concat() method is used to merge two or more arrays in an adjacent way.

Note - The method does not change the existing arrays but instead return a new array.

const nameOfArray1=[“codedamn”]; 
const nameOfArray2=[“is”, “best”];
Const concatedArray=nameOfArray1.concat(nameOfArray2);
Console.log(concatedArray);
//output
[”codedamn”,” is”,” best”]

slice()

This method returns a new array coping all the elements from index start to the end but it does not include the end. If the case start and end are negative positions from the array, the end will be assumed.

arr.slice([start],[end])
let nameOfArray=[“C”,” O”,” D”,” E”,” D”,” A”,” M”,” N”];
console.log(nameOfArray.slice(1,3));
//output
[“O”,” D”]
Console.log(nameOfArray.slice(-2));
//output
[“M”,” N”]  (copy from -2 till the end )

Hope you have learnt something new. Thanks for reading.

Keep learning! 🔥