Skip to main content

JavaScript for-loop, forEach, Map, Filter and Sort Functions | forEach() .map(), .filter() .sort()

//Exploring for-loop, forEach, Map, Filter & Sort Functions
//Write the code to get the array of names from the given array of users
//pick only active users
//sort users by age ascending

Result URL link: https://playcode.io/1943698

When you loop through (or iterate through) an array, the first thing you think of is probably a for loop, .forEach(), .map(), and .filter() are all just other ways of iterating through arrays to perform a specific task on each array element and are called methods.

//Exploring for-loop, forEach, Map, Filter & Sort Functions
//Write the code to get the array of names from the given array of users
//pick only active users
//sort users by age ascending
var users=[
  {id:1, name:'Anil', isActive:true, city:'Noida', age:39},
  {id:2, name:'Alok', isActive:true, city:'GR Noida', age:40},
  {id:3, name:'Sunil', isActive:false, city:'Delhi', age:29},
  {id:4, name:'Harsh', isActive:true, city:'GBZ', age:27}
];

/* Solution 1 - Level 1*/
let names1=[];

for(let i=0; i < users.length; i++ ){
  if(users[i].isActive)
      names1.push(users[i].name);
}
console.log("Solution 1 :", names1);


/*  Solution 2  - Level 2*/
let names2=[];
users.forEach((user)=>{
  if(user.isActive){
    names2.push(user.name);
  }
});
console.log("Solution 2 :", names2);

/* Sort function - descending order default
users.sort((a,b) => a.age < b.age ? -1:1)
console.log("Sort 2 :", users);
*/
/* Sort function - ascending order
users.sort((a,b) => a.age > b.age ? 1:-1)
console.log("Sort 2 :", users);
*/

/*Solution 3 - Level 3*/
let result =users.filter(x=>x.isActive)
.sort((a,b) =>a.age > b.age ? -1:1)
.map(x=>x.name);

console.log('Solution 3 :',result);