Array Methods In JavaScript

Array Methods In JavaScript

·

2 min read

Array

  • It is the collection of elements of different data types.

  • It is of dynamic size.

  • we can access the elements of array by indexes. The index start from 0 to size_of_array - 1.

Example:

let arr=[1,2,3,"Hello","Hai"]

Output:

[1,2,3,'Hello','Hai']

Lets see some of the widely used methods in Javascript.

map()

It is used to perform a set of operations which are mentioned in function to each element of array and store that result in a new array.

Example:

let arr=[1,2,3,4,5];
let result=arr.map(arr=>arr*2);
console.log("The result is", result);

Output:

[2,4,6,8,10]

filter()

It creates a copy of the array and displays the elements only which satisfies the condition of the function which we have defined.

Example:

let arr=[1,2,3,4,5];
let result=arr.filter((arr)=>arr%2==0);
console.log(result);

Output:

[2,4]

reduce()

It is used to reduce the array into a single value by applying the reducer function against the previous and current element.

Example:

let arr=[1,2,3,4,5];
let sum=arr.reduce((previous_element,current_element)=> previous_element+current_element,0);
console.log(sum);

forEach()

It is an inbuilt javascript method used to iterate over the elements in array.

Example:

let arr=[1,2,3,4,5];
arr.forEach(element=>console.log(element*100));

Output:

sort()

It is used to sort the elements in the array. where strings are sorted on string comparisons and numbers are sorted on numerical comparisons.

Example:

arr=[1,9,2,4,6,0]
arr.sort()

Output:

[0,1,2,4,6,9]

find()

This find method will return the first element which satisfies the condition present in the function or else it returns undefined.

Example:

let arr=[1,2,3,4,5];
let found=arr.find((element)=>element>2);
console.log(found);

Output:

3