Javascript::Most useful array method

After seeing lots of resources and from my experience I found some of the most useful array methods which need to know as a javascript developer. In this article, we will talk about some most popular and widely used array methods in javascript. Let's get started.

1) Array.forEach Method

Syntax:

Array.forEach(callback(currentvalue [,index[,array]])[,thisArg])  

For   Example:
const names=['John', 'Rock', 'David', 'Rahul' ];
names.forEach(name=>console.log(name))
Output:
"John" "Rock" "David" "Rahul"
Demo Code Pen  

Here, inside the forEach loop callback function, each element of the array is automatically passed as the first parameter of the function.

The equivalent for loop code for the above example looks like this:

Demo Code Pen 

Note:forEach is only used to loop through the array and perform some processing or logging. It does not return any value, even if you explicitly return a value from the callback function (this means that the returned value comes as undefined in the above example).

In all the above examples, we have used only the first parameter of the callback function. But the callback function also receives two additional parameters, which are:

index - the index of the element which is currently being iterated


array - original array which we're looping over 


const names=['John', 'Rock', 'David', 'Rahul' ];


names.forEach((name, index,array)=>{


console.log(name,index,array)


})


output:


John 0 ['John', 'Rock', 'David', 'Rahul' ]


Rock 1 ['John', 'Rock', 'David', 'Rahul' ]


David 2 ['John', 'Rock', 'David', 'Rahul' ]


Rahul 3 ['John', 'Rock', 'David', 'Rahul' ]


Code Pen Demo


Why use forEach, not for loop:


Using a forEach loop makes your code shorter and easier to understand


When using a forEach loop, we don't need to keep track of how many elements are available in the array. So it avoids the creation of an extra counter variable.


Using a forEach loop makes code easy to debug because there are no extra variables for looping through the array


The forEach loop automatically stops when all the elements of the array are finished iterating.


2) Array.map Method


The Array map method is the most useful and widely used array method among all other methods.


Syntax:


Array.map(function callback(currentValue[, index[, array]]) {


 // Return element for new_array


}[, thisArg])


The map method executes a provided function once for every element in the array and it returns a new transformed array.


Take a look at the below code:


const names=['John', 'Rock', 'David', 'Rahul' ];


const newArray=names.map((name)=>{


return name.toUpperCase()


})


console.log(newArray); // ['JOHN', 'ROCK', 'DAVID', 'RAHUL' ];


Code Pen Demo


Note: The map method returns a new array that is of the exact same length as the original array but the forEach method is only used for looping and does not return anything back.


Why use map method:


It helps quickly generate a new array without changing the original array


It helps generate an array with dynamic content based on each element


It allows us to quickly extract any element of the array


It generates an array with the exact same length as the original array


3 ) Array. find method 


syntax:


Array.find(callback(element[, index[, array]]) {


    // Return element for new_array


}[, thisArg])


The find method returns the value of the first element in the array that satisfies the provided test condition.

The find method takes a callback function as the first argument and executes the callback function for every element of the array. Each array element value is passed as the first parameter to the callback function.


Suppose, we have a list of countries like this:


const  countries = [


 { name: "Estonia", language:'Estonian' }, 


{ name: "Lithuania", language:'Lithuanian' },


 { name: "Latvia", language:'Latvian' },


 { name: "Russia", language:'Russain' }



];


and we want to get the record for the countries which name is Latvia. In this case, we can use the find method as shown below:


const country = countries.find(function (country) {


  return  country.name.indexOf('Latvia') > -1;


});



console.log(country); //  { name: "Latvia", language:'Latvian' }


Code Pen Demo


The equivalent for loop code for the above example looks like this:


const  countries = [


 { name: "Estonia", language:'Estonian' }, 


{ name: "Lithuania", language:'Lithuanian' },


 { name: "Latvia", language:'Latvian' },


 { name: "Russia", language:'Russain' }



];


let country;


for(let i = 0; i < countries.length; i++) {


  if(countries[i].name.indexOf('Latvia') > -1) {


    country = countries[i];


    break;


  }


}



console.log(country); //  { name: "Latvia", language:'Latvian' }


Code Pen Demo


Why use find method:


It allows us to quickly find any element without writing a lot of code


It stops looping as soon as it finds a match so there is no need for an extra break statement


4) The Array.findIndex Method

Syntax:

Array.findIndex(callback(element[, index[, array]])[, thisArg])


The findIndex method returns the index of the first element in the array that satisfies the provided test condition. Otherwise, it returns -1, indicating that no element passed the test.

const  countries = [


 { name: "Estonia", language:'Estonian' }, 


{ name: "Lithuania", language:'Lithuanian' },


 { name: "Latvia", language:'Latvian' },


 { name: "Russia", language:'Russain' }



];


const index=countries.findIndex((country)=>{


return country.name.indexOf('Latvia') > -1;


});


console.log(index): // 2


Code Pen Demo 


The equivalent for loop code for the above example looks like this:


const  countries = [


 { name: "Estonia", language:'Estonian' }, 


{ name: "Lithuania", language:'Lithuanian' },


 { name: "Latvia", language:'Latvian' },


 { name: "Russia", language:'Russain' }



];


let index= -1;


for(let i=0; i< countries.length; i++){


if(countries[i].name.indexOf('Latvia') > -1){


index =i;


break;


}


}


console.log(index);// 2;


Code Pen Demo


Why use findIndex method:


It allows us to quickly find the index of an element without writing a lot of code


It stops looping as soon as it finds a match so there is no need for an extra break statement


We can find the index using the array find method also, but using findIndex makes it easy and avoids creating extra variables to store the index


5) The Array.filter Method

Syntax:

Array.filter(callback(element[, index[, array]])[, thisArg])


The filter method returns a new array with all the elements that satisfy the provided test condition.


The filter method takes a callback function as the first argument and executes the callback function for every element of the array. Each array element value is passed as the first parameter to the callback function.

const  countries = [


 { name: "Estonia", language:'Estonian' }, 


{ name: "Lithuania", language:'Lithuanian' },


 { name: "Latvia", language:'Latvian' },


 { name: "Russia", language:'Russain' },


{ name: "Estonia", location:'Europe' }



];


const country=countries.filter((country)=>{


return country.name.indexOf('Estonia') > -1;


});


console.log(index); //  [ { name: "Estonia", language:'Estonian' }, { name: "Estonia", location:'Europe' } ];


Code Pen Demo


The equivalent for loop code for the above example looks like this:


Please check Code Pen Demo


Why use Array.filter Method:


It allows us to quickly find all the matching elements from the array


It always returns an array even if there is no match, so it avoids writing extra if conditions


It avoids the need of creating an extra variable to store the filtered elements


6) The Array.every Method

Syntax:

Array.every(callback(element[, index[, array]])[, thisArg])

The every method tests whether all elements in the array pass the provided test conditions and returns a boolean true or false value.


Suppose we have an array of numbers and we want to check if every element of the array is a positive number. We can use the every method to achieve it.


let numbers = [10, -30, 20, 50];


let allPositive = numbers.every(function (number) {

  return number > 0;

});

console.log(allPositive); // false 


numbers = [10, 30, 20, 50];


allPositive = numbers.every(function (number) {

  return number > 0;

});

console.log(allPositive); // true


Imagine you have a registration form, and you want to check if all of the required fields are entered or not before submitting the form. You can use the every method to check for each field value easily.


window.onload = function () {

  const form = document.getElementById('registration_form');

  form.addEventListener('submit', function (event) {

    event.preventDefault();

    const fields = ['first_name', 'last_name', 'email', 'city'];

    const allFieldsEntered = fields.every(function (fieldId) {

      return document.getElementById(fieldId).value.trim() !== '';

    });


    if (allFieldsEntered) {

      console.log('All the fields are entered');

      // All the field values are entered, submit the form

    } else {

      alert('Please, fill out all the field values.');

    }

  });

};

Code Pen Demo


why use Array. every Method:

It allows us to quickly check if all the elements match certain criteria without writing a lot of code

Post a Comment

0 Comments