JavaScript – Every(), Filter(), Map(), Sort() and Reduce() Methods Tutorial

There are few very useful methods in JavaScript like every(), filter(), map(), sort() and reduce(). We are using these two arrays to increase our JS knowledge. Here are example arrays you may copy them. 

const companies = [
  {name: "Company One", category: "Finance", start: 1981, end: 2003},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008},
  {name: "Company Three", category: "Auto", start: 1999, end: 2007},
  {name: "Company Four", category: "Retail", start: 1989, end: 2010},
  {name: "Company Five", category: "Technology", start: 2009, end: 2014},
  {name: "Company Six", category: "Finance", start: 1987, end: 2010},
  {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
  {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
  {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
];

const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];

The JS method, every() will check for the conditions passed against every value of the array and return true or false. For example we want to check that every value of ages array is greater than 5 or not? We can use every() method.

const flag = ages.every(age => age => 5);
console.log(flag);

The JS method, filter() will filter the records according to the condition provided. 

 const canDrink = ages.filter(age => {
 	if(age >= 21){
 		return true;
 	}
 });

console.log(canDrink);

We can also use Arrow function syntax. 

const cannotDrink = ages.filter(age => age < 21);
console.log(cannotDrink);

We can get values from objects array like this. 

const retailCompanies = companies.filter(company => company.category == 'Auto');
console.log(retailCompanies);

Another function map() creates a new array by applying the condition we put inside it. 

const companiesNames = companies.map( company => company.name )
console.log(companiesNames)

We can also perform math operations across the numbers array and create new array. 

const agesDouble = ages.map(age => age*2)
console.log(agesDouble);

The JS function sort() will sort objects array or simple arrays. It is a very handy function. 

 const sortedCompanies = companies.sort((a, b) => ((a.start > b.start ) ? 1 : -1 ));

Above we are sorting companies array on the basis of start year. Sorting the numbers array is easier. 

 const sortedAges = ages.sort((a, b) => b - a);
 console.log(sortedAges);

The method reduce() performs basic operations on arrays and returns one singular value. 

 let ageSum = ages.reduce((total, age) => total + age, 0)

For object arrays we can write this. 

const totalYears = companies.reduce( (total , company) => total + (company.end - company.start), 0);

At last here I am performing all operations on one array and returning the value. 

ages.map(age => age * 2).filter(age => age >= 40).sort((a, b) => a - b).reduce((total,age) => total+age, 0 );