Array methods in Javascript aka Javascript Array Methods Cookbook

 Javascript Array Methods

The diagram represents how the array method works.



Javascript array methods are very useful in every aspect of javascript programmers. Let see what and all modern array methods are there in Javascript.

  • find
  • filter
  • findIndex
  • map
  • some
  • every
  • reduce

Find Method

The image represents how the find method works.

The find method helps to find a single result from an array. To find the element from the array, the find method's callback function should return an expression that evaluates true or false. The search will start from the 0th index once when the conditions match, it will return the current element and breaks the loop. If none of the elements are found, it will return undefined.

🎢 The syntax for find method:


["element1""element2""element3"].find((element,index)=>{
  //other codes here
  return true | false // must return true or false
}); // returns you a matched element or undefined


🚀 Example for find method:

Let us take an array of objects that contains some user data i.e userDetails.


const userDetails = [
  {
    id:1,
    name:"Mike",
    age:20
  },
  
  {
    id:2,
    name:"Dustin",
    age:19
  },
  {
    id:3,
    name:"Will",
    age:17
  },
  {
    id:4,
    name:"El",
    age:18
  },
  
  {
    id:5,
    name:"Nancy",
    age:22
  },
  {
    id:6,
    name:"Jonathan",
    age:25
  }
]


❌ Without find method:

Let see how to achieve the filter method using traditional javascript and check how many lines of code that we can save. Let us use userDetails to find out id = 3;


let userFound;

for (let i = 0i < userDetails.lengthi++) {
  if (userDetails[i].id === 3) {
    userFound = userDetails[i];
    break;
  }
}

console.log(userFound);



✅ With find method:

Let us see how we can achieve the above method to find the id=3 from userDetails using the filter method.


// Code 1

let foundUser = userDetails.find(obj=>{
  return obj.id === 3;
});


Piece of cake right 🍰! We have reduced around 70% of lines of code from the traditional method. It's not over we can even write this function in a single line of code using the advantage of ES6 arrow functions.


let foundUser = userDetails.find(obj => obj.id === 3);


Since the // Code 1 has a single line of return statement we can ignore the curly braces and the return statement. 

Cool right? You can write these types of functions to improve your code quality and readability. This will make other devs feel like you are more experienced. Let's jump to the next topic called the filter method.

Filter Method:

The image represents how the filter method works.

The filter method is the same as the find except it will return all its findings in an array. The iteration here will start from the 0th index to the end of the array.

🎢 The syntax for filter method:


["element1""element2""element3"].filter((element,index)=>{
  //other codes here
  return true | false // must return true or false
}); // returns you an array of matched elements or an empty array


🚀 Example for filter method:

Let us take the same array of objects that contains some user data i.e userDetails.

const userDetails = [
  {
    id:1,
    name:"Mike",
    age:20
  },
  
  {
    id:2,
    name:"Dustin",
    age:19
  },
  {
    id:3,
    name:"Will",
    age:17
  },
  {
    id:4,
    name:"El",
    age:18
  },
  
  {
    id:5,
    name:"Nancy",
    age:22
  },
  {
    id:6,
    name:"Jonathan",
    age:25
  }
]


❌ Without filter method

Let us filter out the users who are 20 and above using traditional javascript.


let usersWhoAre20Above = []; // initially empty

for (let i = 0i < userDetails.lengthi++) {
  // validating for 20 and above
  if (userDetails[i].age >= 20) {
    // pushing users to array when condition is validated to true
    usersWhoAre20Above.push(userDetails[i]);
  }
}

console.log(usersWhoAre20Above)

// will return 

// [
//   {
//     id: 1,
//     name: "Mike",
//     age: 20
//   },
//   {
//     id: 5,
//     name: "Nancy",
//     age: 22
//   },
//   {
//     id: 6,
//     name: "Jonathan",
//     age: 25
//   }
// ]

Wow, we have filtered the list of users who are 20 and above. Let us use the filter method to optimize our code.

✅ With filter method:


let usersWhoAre20Above = userDetails.filter(obj => {
  return age >= 20
})


🍰 We again reduced 70% of code from the previous example. Let us use the advantage of ES6 arrow functions to reduce the above method to a single line.


let usersWhoAre20Above = userDetails.filter(obj => obj.age >= 20);


See how simple it is. Let's jump to the next section findIndex.

Find Index Method:

The image represents how the findIndex method works.

From the name itself, you can identify, that the findIndex will return you the index of the array based on the condition. If none of the results are found it will return -1.

🎢 The syntax for findIndex method:


["element1""element2""element3"].findIndex((element,index)=>{
  //other codes here
  return true | false // must return true or false
}); // returns you index (integer) of matched elements or -1


🚀 Example of findIndex method

Let us compare ❌ without the findIndex method and ✅ with the findIndex method like we did before to demonstrate how to reduce the lines of code. Let us use userDetails throughout the whole example. In the below example, we are going to find out the index of id = 2.

❌ Without findIndex method: 


let userIndex = -1// initially empty

for (let i = 0i < userDetails.lengthi++) {
  // validating for 20 and above
  if (userDetails[i].id === 2) {
    // assigning the currrent index to userIndex variable
    userIndex = i;
    // breaking the loop to avoid unnecessary iterations 
    break;
  }
}

console.log(userIndex// prints 1


Wow, we have found out the index of id=2 without using our findIndex method. Let us use find index method to reduce to fewer lines of code.

.✅ With findIndex method:


let userIndex = userDetails.findIndex(obj => {
  return obj.id === 2;
}); // now userIndex = 1


🍰 We have reduced around 70% of lines of code from the traditional javascript method. Let us take advantage of the ES6 arrow functions feature to avoid further lines of code.


let userIndex = userDetails.findIndex(obj => obj.id === 2);


Look how simple it is. Let's jump to the next section map.

Map method:

The image represents how the map method works.

This is the most widely used array method. This helps you to restructure or create a new array based on the input array. It will return you the same length as the input array.

🎢 The syntax for map method:


["element1""element2""element3"].map((element,index)=>{
  //other codes here
  return <some element that we want to return>
}); // returns you a array based on return statement

// output array length will be the same as the input array.

🚀 Example of the map method:

Lets take an array let arr = [1,2,3,4,5,6]; . We are going to double it up to [2,4,6,8,10,12] using traditional javascript without using map method.

❌ Without using the map method:


let arr = [123456];
let doubled = []; // empty array to store results.
for (let i = 0i < arr.lengthi++) {
  let doubledValue = arr[i] * 2// doubling the value
  doubled.push(doubledValue); // pushes the doubled value to the doubled array
}

console.log(doubled);
// prints [2,4,6,8,10,12]


Easy right. We can even make this easier than as it is using the map method.

✅ With map method:


let arr = [123456];
let doubled = arr.map(obj => {
  return obj * 2// will add this result to every iteration
}); // returns same result as traditional function we seen before.


Using the advantage of the ES6 arrow function, we are going to make this function even leaner.


let doubled = arr.map(obj => obj * 2);


🍰 Piece of cake right! Using the map method can sound you the pro developer.

Some method:

The image represents how the some method works.


Some method will return you the boolean (i.e true or false) based on the condition. This iteration will start from the 0th index till the match is found. If any one of the matches is found, it will return you true else if none of them matches, then it will return false. 

🎢 The syntax for some method:


["element1""element2""element3"].some((element,index)=>{
  //other codes here
  return true | false // must return true or false
}); // returns you a boolean i.e true or false


🚀 Example for some method:

Let us take the userDetails and we are gonna find out that Are we have any users whose age is below 18? Let us compare the traditional and some method as we did before.

const userDetails = [
  {
    id: 1,
    name: "Mike",
    age: 20
  },

  {
    id: 2,
    name: "Dustin",
    age: 19
  },
  {
    id: 3,
    name: "Will",
    age: 17
  },
  {
    id: 4,
    name: "El",
    age: 18
  },

  {
    id: 5,
    name: "Nancy",
    age: 22
  },
  {
    id: 6,
    name: "Jonathan",
    age: 25
  }
]
let isBelow18 = false// initially set to false
for (let i = 0i < userDetails.lengthi++) {
  if (userDetails[i].age < 18) {
    isBelow18 = true// setting to true if anyone is below 18
    break// breaking the loop to avoid unwanted iteration
  }
}

console.log(isBelow18);

//prints true because "Will" is 17 years old


✅ With some method:

Let us simplify the above example using some method to avoid some lines of code.


let isBelow18 = userDetails.some(obj => {
  return obj.age < 18;
});


Piece of 🍰 right! Let us use the advantage of ES6 arrow functions to reduce further more lines of code.


let isBelow18 = userDetails.some(obj => obj.age < 18);

 
Wow, we did it. Some method make life easier 👍. 

Every method:

The image represents how every method works.

Every method will return you the boolean (i.e true or false) based on the condition. This iteration will start from the 0th index till the end of the array. If all of the elements match the condition, it will return you true else if any one of them didn't match, then it will return false. 

🎢 The syntax for every method:


["element1""element2""element3"].every((element,index)=>{
  //other codes here
  return true | false // must return true or false
}); // returns you a boolean i.e true or false based on all result matches


🚀 Example for every method:

Let us take the same array userDetails to find out every user is greater than 15 years of age.

❌ Without every method:

I am demonstrating how to achieve every method in traditional javascript.

let isEveroneAbove15 = true// initially set to true
for (let i = 0i < userDetails.lengthi++) {
  if (userDetails[i].age < 15) {
    isEveroneAbove15 = false// setting to true if anyone is below 15
    break// breaking the loop to avoid unwanted iteration
  }
}

console.log(isEveroneAbove15);

// prints true since all of the users are over 15

Great! we have found all of them are over 15 years old user. Let us make our code lighter by using every method.

✅ With every method:

let isEveroneAbove15 = userDetails.every(obj=>{
  return obj.age > 15;
});

Alright, we almost did it. One more thing is remaining guess what?. Yeah, it's time to use the advantage of the ES6 arrow functions.


let isEveroneAbove15 = userDetails.every(obj => obj.age > 15);


 Piece of 🍰 right, we did it. We have reduced almost 70% of lines of code from the traditional javascript method.

Reduce method:

The image illustrates how reduce method works.


Reduce method helps you to reduce the array to some value. It keeps recording the previous value, it helps in evaluating an array to some value, For example, finding the sum of the array, average of the array, concatenation of elements in an array, etc.,

🎢 The syntax of reduce method:

["element1""element2""element3"].reduce((accumulatorcurrentindexinputArray=> {
  return someExpression// will be the accumulator for next iteration
}, initialValue)


🚀 Example for the reduce method:

Let us use the userDetails array to find the average age of our users.

❌ Without using reduce method: 

Using input array userDetails, to find out the average users


let averageAge = 0// set to 0 initially
let sum = 0;
for (let i = 0i < userDetails.lengthi++) {
  sum += userDetails[i].age
}

averageAge = sum / userDetails.length;

console.log(averageAge// 20.166666666666668

✅ With reduce method:


const sum = (userDetails.reduce((accumulatorcurrent=> {
  return accumulator + current.age;
}, 0))

const averageAge = sum / userDetails.length
// 20.166666666666668


Using the reduce method we have reduced almost 40% of the code. Next, we are going to utilize the advantage of the ES6's arrow function in javascript. 


let sum = userDetails.reduce((accumulatorcurrent=> accumulator + current.age0);
let averageAge = sum / userDetails.length; // 20.166666666666668



🎉 Thanks for reading this article. I am very happy that you spent your time on something good. I hope this article gave you a clear idea of the array methods of javascript. Please comment and share this article with someone who really needs this. Thanks again and stay connected for more interesting posts.

👀 If you are looking for Javascript's ES6 cookbook, click here.



2 Comments

Previous Post Next Post