Array Methods in JavaScript — Applied

Yogesh Patil
4 min readMay 9, 2021

JavaScript has been along for quite a while now, and it has proven to be one of the most versatile language ever. JavaScript, having wedged itself in all the browsers, is one of the most popular frontend programing language of choice. For quite a while now, JavaScript have been shining in server side development too, thanks to NodeJS.
With increasing use of JavaScript, you might run into conditions where you need to work with array of data to filter, map, reduce or derive availability of certain fields or values in that array. This blog goes through the common methods present in JavaScript engine that can be used to achieve your results quick and effective.

Getting Started

Before we begin, lets discuss the runtime and some primer. We would be using chrome developer tools as the JavaScript engine to execute what is discussed here.

How are Arrays declared? There are two methods to declare arrays in java script,

// Literal Method
var array = [“this”, “is”, “an”, “array”, “of”, “strings”]
// Using the new keyword
var array = new Array(“this”, “is”, “another”, “array”, “of”, “strings”)
Create Array in JavaScript
Create Array in JavaScript

Array Methods

While there are quite a few methods that you can use on an array, this article would be focusing on,

forEach(), filter(), map(), some(), every() and reduce()

Lets work on an example array of employees.

var employees = [
{
id: 100,
name: "John",
salary: 50000,
department: "finance"
}, {
id: 101,
name: "Mary",
salary: 45000,
department: "finance"
}, {
id: 102,
name: "Jai",
salary: 90000,
department: "hr"
}, {
id: 103,
name: "Rio",
salary: 30000,
department: "admin"
}
]

arrary.forEach()

This is the method you would consider while looping over your array. Common example would be printing some field value on console. This method expects a callback function which would be passed the current element to be processed, the index of the current element and optional array.

Consider, you want to print out the sum of all the salary a company dispenses, you can do the following;

var totalSalary = 0;
employees.forEach(function(employee, index) {
sum += employee.salary;
});
console.log("The total salary dispensed", totalSalary); // 215000

array.filter()

What if you want to work on specific records based on a condition. arrayfilter() is an excellent way to acheive this. Based on the predicate callback, this method will return an array containing only the requiried elements.

Lets say we want to print the names of all the employees whose salary is greater than 50000,

var nicelyPaidEmployees = employees.filter(function(employee) {
return employee.salary >= 50000;
});
// You can also chain the above output to the forEach below
nicelyPaidEmployees.forEach(function(employee) {
console.log("Nicely paid Employee:", employee.name);
})
// Nicely paid Employee: John
// Nicely paid Employee: Jai

array.map()

If you want the array to hold a different representation, or convert the array into an array of some computed values, you can use the map method of array. This method takes in a transform callback which takes in an element and returns the transformed value for that element.

Lets say considering the array of employees, you want an array of just the employee names, you can do the following,

var empNames = employees.map(function(emp) {
return emp.name;
})
// empNames => ["John", "Mary", "Jai", "Rio"]

array.some()

This method is handy when you want to test your array for inclusion of element or testing weather a certain value is present in the elements of the array. Like array.filter(), this method takes in a callback with element as the input and returns true or false depending on your condition. Unlike filter, this method returns at the first sign of truthy value.

Lets say we want to know if the list of employees has any employee in the hr department, you can do the following

var isHrEmployeeInList = employees.some(function(emp) {
return emp.department === 'hr';
})
// isHrEmployeeInList is true.
// To test if the method is called only once, use below
employees.some(function(emp) {
console.log("Processed ", emp.name);
return emp.department === 'finance';
})
// Processed John
// Output: true

array.every()

This method is used when you need to check existence of some data in all the elements of the array, or check if all the elements of the array satisfy a condition. Like filter, this method takes a predicate callback with element as the input and returns boolean value. This method returns true when all the elements in the array fulfill the predicate passed.

Lets say, you need to check if all the employees have salary above 10000, you could do something like

var areAllAbove10k = employees.every(function(emp) {
return emp.salary > 10000;
});
// areAllAbove10k -> true

array.reduce()

This method is usually used to process the array and get a different representation for the array of elements. This method takes a reducer callback which will work on a default/previous reducer’s output and current element to provide a required output.

The syntax of reduce function is array.reduce(reduceCallback, initialValue)

Lets consider some examples to understand this.

// You need to get the sum of the salary spent on the employees
var sumOfSalary = employees.reduce(function(prevReturn, currentEmployee) {
return prevReturn += currentEmployee.salary;
}, 0);
// sumOfSalary => 215000

// You need to create an map. This map would be between the departments and the list of employee names.var departmentMap = employees.reduce(function(prevMap, currentEmp) {
var dep = currentEmp.department;
if( ! prevMap[dep] ) {
prevMap[dep] = [];
}
prevMap[dep].push(currentEmp.name);
return prevMap;
}, {});
// departmentMap -> {"finance": ["John","Mary"], "hr":["Jai"], "admin": ["Rio"]

Conclusion

This blog takes an example and uses the popular array methods for array data processing. You can chain the output of these array methods to get your desired output. There are more array functions, but these are the methods I use and am comfortable with. Hope to see more developers using JavaScript array methods.

Thank you…

--

--