Most Important Array functions in Javascript
ddev2636
Posted on April 13, 2022
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;
}
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>";
}
The output comes to be
1: 1
2: 2
3: 3
4: 4
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);
It will display the square root of every element.
1,2,3,4,5
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;
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)]
Posted on April 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024
November 22, 2024