Dot Net For All

JavaScript Array Methods every developer should know

Hello Friends, In this article I will walk you through some of the very important JavaScript array methods every developer should be aware of. This is a concise list of the JavaScript array methods which will help you to work more efficiently.

Important JavaScript Array Methods

Before starting to know about the important JavaScript methods, I should walk you through the data which we will be working on.

Below is the collection of the students who are good friends as well and but they have studied different subjects. The total is based on the number of subjects opted by each student.

const students = [
{ first: 'Albert', last: 'Einstein', marks: 879, total: 1000 },
{ first: 'Isaac', last: 'Newton', marks: 643, total: 700 },
{ first: 'Galileo', last: 'Galilei', marks: 564, total: 600 },
{ first: 'Marie', last: 'Curie', marks: 867, total: 900 },
{ first: 'Johannes', last: 'Kepler', marks: 571, total: 600 },
{ first: 'Nicolaus', last: 'Copernicus', marks: 473, total: 500 },
{ first: 'Max', last: 'Planck', marks: 858, total: 900 },
];

JavaScript Filter method

Filter method is used to filter out the array items based on some criteria or condition. This will return a filtered array.

For our examples suppose, you want to get all the students with more than 95% marks. There can be many ways to you can use the Filter method. First way is to use the arrow functions and the other one is by using the callback functions.

Below is the code example for both of these scenarios.

  var filteredstudents1 = students.filter(item => {
        var percentage = (item.marks/item.total) * 100;      
        return percentage > 70;        
      });

    var filteredstudents = students.filter(function(item){
      var percentage = (item.marks/item.total) * 100;    
      if(percentage > 95)
        return true;
    });

JavaScript Map Method

The next important JavaScript method in the list is the Map method.

Map returns the same number of items in the array. It just transforms the item and return a newly created object out of the original one.

Let see the example.

In the first example below, I am returning a new array with the new object of full name and the percentage.

In the second example, I am returning an array of string. The full name is the string.

var arrayWithPercentage = students.map(item => {
    var percentage = (item.marks/item.total) * 100;     
    var newObj ={
        'Name': `${item.first} ${item.last}`,
        'percentage': percentage
    }
    return newObj;
});

var fullName = students.map(item => `${item.first} ${item.last}`);

console.table(arrayWithPercentage);
console.table(fullName);

JavaScript Sort Method

Sort method is used to sort the number of items in the array. Specific condition is used to sort array items.

Finally a nice example for this one as well.

I want to sort all the students in array by first name alphabetically.

var sortedArray = students.sort((a,b) => {
    if(a.first > b.first){
        return 1;
    } else{
        return -1;
    }
});

console.table(sortedArray);

Much cleaner way to write the same logic in one line of code.

var sortedArray = students.sort((a,b) => a.first > b.first ? 1 : -1);

JavaScript Reduce Method

Reduce method is used to loop over the array items and return a specific output.

Lets try to understand it in a better way.

From the above array items, if you want to find the total marks obtained by all the students. How you would do it? You will declare a variable and loop over all the elements and keep adding the mark to the variable.

 var totalMarks = students.reduce((total , student) => {
      return total + (student.marks);
    }, 0);

Reduce method takes care of all the verbosity of creating a loop and initializing a variable.

One more very nice example of reduce is, if you want to find the number of time an item is present in an array.

var student = ['Vikram', 'Vikram', 'Martin', 'Martin', 'Martin', 'Vikram', 'Suresh',
'Suresh', 'Martin', 'Tim'];

In the above string array, I want to find how many times each specific string is repeated. For example, how many times ‘Vikram’ is there or ‘Martin’ is there.

var instanseCount = student.reduce((obj, item) => 
{if(!obj[item])
    { 
        obj[item] = 0;
    } 
    obj[item]++; 
    return obj;
} , {} );

In the above code, I am passing a blank object as first parameter to the arrow function. This blank object will be used to carry the count of items in the array.

The logic is simple, if the item is not present in the object than create a property of that item initialized with zero otherwise increment it by one.

Conclusion:

In this article I have discussed some of the most important JavaScript array methods which can help you as a developer. These JavaScript methods helps to reduce the verbosity and development time.

References:

JavaScript30

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview