DEV Community

ddev2636
ddev2636

Posted on

Most Important Array functions in Javascript

As a beginner, I also face difficulty in remembering all the functions associated with a particular topic. So I thought of writing about some important and widely used array functions in javascript which I personally feel are very useful and a must know for beginners. However, one should have at least a basic idea of all the functions.

1. Filter()

The Filter() method creates a new array filled with elements that pass a test provided by a function. However it does not change the original array.
For example,

const numbers = [32, 33, 16, 40];
const result = numbers.filter(checkNumber);

function checkNumber(number) {
  return number >= 30;
}
Enter fullscreen mode Exit fullscreen mode

The filter will return [32,33,44] as these elements are greater than 30.

2. forEach()

The forEach() method calls a function for each elements in an array. It's somewhat similar to the for loop for all elements.
For example,

let text = "";
const numbers = [1,2,3,4]
numbers.forEach(functionMe);
document.getElementById("para").innerHTML = text;
function functionMe(item, index) {
  text += (index+1) + ": " + item + "<br>"; 
}
Enter fullscreen mode Exit fullscreen mode

The output comes to be

1: 1
2: 2
3: 3
4: 4
Enter fullscreen mode Exit fullscreen mode

3. map()

The map() method creates a new array from the results of calling a function for every element.
For example,

const numbers = [1, 4, 9, 16, 25];
document.getElementById("para").innerHTML = numbers.map(Math.sqrt);
Enter fullscreen mode Exit fullscreen mode

It will display the square root of every element.

1,2,3,4,5 
Enter fullscreen mode Exit fullscreen mode

4. Splice()

Splice() method overwrites the original array by adding or removing elements.
for example,

const avengers = ["Captain America", "Iron Man", "Hulk", "Thor"];

fruits.splice(3, 0, "spider man", "Dr. Strange");
// here 3 signifies index, 0 signifies that no element is to be deleted .
//If we wish to delete some elements ,then index and number of elements to be deleted should be provided.

document.getElementById("para").innerHTML = fruits;
Enter fullscreen mode Exit fullscreen mode

this will add 2 elements at the index 3.

Hope this helps some peeps new to coding and web development.
For more detailed explanation of these topics you may follow this playlist [(https://www.youtube.com/playlist?list=PLgBH1CvjOA62PBFIDq55-S6Beivje30A2)]

Top comments (0)