Smart {Code};

samuel-martins

Hi there, I am a full-stack developer. I love sharing my knowledge of development technologies and programming in general. Subscribe to get notified anytime I publish.

7 Likes Share

Arrays are one of the most common things that you’re going to use as a programmer. In this article, I’m going to be covering important JavaScript array methods that are going to make your life as a developer so much easier. As an example, I am going to use a student array of student objects for all of these different array methods

. . .

const students = [
        {name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

filter()

So let’s assume that we want to get all of the students in this list whose ages are less than or equal to 24. All we would need to use is the filter method to filter out every student that’s not under 24.


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

/*

this filter method just takes a single function, 
which is going to have one parameter of student which 
is every student/item in the array. we'd need to 
return a true or false statement on whether or 
not we want to include them in the new array

*/

const filteredStudents = students.filter((students) => {
	return students.age <= 24        
})

/* 

This line basically stashes all of the students 
whose ages are less than a 24 in the new 
filteredStudents array 

*/

console.log(filteredStudents)

This filtered array method is super easy to use. All you do is return true or false for each item. If it’s true, it is added into the new array, and if it’s false, it is not. The great thing about the filter method and all the other methods in this article is that they actually don’t change the underlying object that you’re filtering over so we can log the students array and it will still have all its items. This is very convenient because we don’t have to worry about changing the old array when we use these new array method to create new arrays.

. . .

map()

map() allows you to take one array and convert it into a new array. In this one, all the items in the new array are going to look slightly different. So let’s just say, we want to get the name of every student. we can get an array of the names by using map().


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

/*
the method takes a single function, with the 
students/items as a parameter here we just 
return what we want in the new array
*/
const studentNames = students.map((students) => {
        return students.name
})

console.log(studentNames)

/*
If we print out these student names, console.log(studentNames)
we get a new array that is just full of all the different
names of the students.
*/
     

This can be done with anything within the array. The method is very useful when you want to take an object for example, and just get the names or a single key, or take one array and convert it into another array. This method is one of the most popular ones in JavaScript arrays.

. . .

find()

This method allows you to find a single object in an array. This is straight forward. Say we want to find a student with the name john,


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

const singleStudent = students.find((students) => {
return students.name === 'john'
})

console.log(singleStudent)
/*
  console.log(singleStudent) will give the everything 
  associated with john in this example, I.e

   Object {
    age: 25,
    name: "john",
    score: 86
  }
  

*/

In this method, the logic is that there is a true or false statement, and it’s going to return the very first array item that evaluates to true.

. . .

forEach()

Unlike these other methods, forEach() does not actually return anything, hence no need for a return statement. Let’s say we need to print out all the names of the students within the student array, we would go about it as:


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

students.forEach((students) => {
  console.log(students.name)
})

/*
  the result is the name property printed out on the 
  console line after line like so

  "sam"
  "john"
  "dean"
  "timothy"
  "frank"

 */

this is going to work very similarly to a for-loop, but it’s going to take a function instead. So, for every single array item, it’s going to do execute the block of code within the function. This approach just makes working with arrays where you need to loop over items so much easier since you don’t have to write out the clunky long for loop syntax as you’d normally have to.

. . .

some()

This method is a bit different than most of our other functions in that, instead of returning a brand new array, it’s actually going to return true or false. So we can check if some of the students in this array are underage,

const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

const hasUnderageStudents = students.some((students) => {
   return students.age < 18
})

console.log(hasUnderageStudents)
/*
  this will return false because there is no 
  underage student in the array.
*/

So if any student item has an age value below 18, the function will return true. The method just checks to see if anything in the array returns true and if it does, the entire thing returns true.

. . .

every()

This method is very similar to some() except for instead checking for at least one item to evaluate to true or false, it checks to make sure every single item falls under a given condition.
if I use the same code used in the some() code example,

const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

const hasUnderageStudents = students.every((students) => {
return students.age < 18
})

console.log(hasUnderageStudents)
// this returns false because there are no ages below 18

If I am to change the condition to one which every item evaluates to true, the whole thing returns true

const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 
const hasUnderageStudents = students.every((students) => {
  return students.age < 40
})

console.log(hasUnderageStudents)
// this will return true because every single age property is below 40

. . .

reduce()

This method is quite different than all the other methods because it is actually doing some operation on the array and returning a combination of all those different operations. Let’s say I wanted the total scores for all the items in the student array, normally one would go for a for loop and add the score every single time, and at the end of the loop, you would print out the total score. To avoid the long process, you can use the reduce() method to do this.


The syntax for the reduced method differs from the other methods. Instead of taking the array itself, it takes an array and a property for what we want to reduce everything into and in our example, score. it also takes a second parameter aside from the function, which is going to be your starting point, and in our case, we want to start our total at zero.


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 
const totalScore = students.reduce((currentTotal, students) => {
  return students.score + currentTotal
}, 0)

console.log(totalScore)
  • As the code reads, we have the reduce() method, which runs a function on every single item inside the array.
  • The first parameter of that function is going to be whatever the previous iteration of this array returned and the second parameter is the actual item in the array.
  • The currentTotal is going to start on the very first iteration with whatever we pass in as the second parameter of the reduce() method which is zero in our case.
  • The first time this reduce() method runs, so we get zero and the ‘sam’ item. So it just does 80 plus zero and returns that, which is 80.
  • The second time the method runs, that return value of 80 becomes the current total, and our next item is ‘john’, so it does 86 plus our current total of 80, which is 166, and puts that back in for the current total. It does that until we get to the very last item in the array, which will output as the total in the totalScore variable.

This method is a bit more confusing, but it is incredibly useful when you need to do some kind of operation cumulatively to all the items in an array, such as grabbing the total price for all the items, daily stock prices e.t.c

. . .

includes()

This method doesn’t take a function as an argument. It takes a single argument. It is usually used in simple arrays that don’t need a lot of heavy operations. Let’s say you have an array of fruits, const fruits = [ ‘mango’, ‘apple’, ‘orange’, ‘pineapple’, ‘lemon’]. a simple way of showing the implementation of the includes() method would be to check if a certain fruit is in the array.


const fruits = [ 'mango', 'apple', 'orange', 'pineapple', 'lemon']

const includesApple = fruits.includes('apple')

console.log(includesApple) 
/* 
this will return true because 'apple' is 
one of the items inside the array. 
*/

. . .

In my opinion, these methods are a must-know for any JavaScript developer because arrays are one of the data structures that are most commonly used for organization. Having a good grasp of these methods will greatly improve your skills and problem-solving ability when it comes to arrays.

Related Posts . . .


 11th Aug 2021

3 Lies Software Developers Put On Their Resume

How many jobs have you applied to this year alone? How many jobs have you landed? Is there a common denominator? Is there an art to job applications? Lately, I have

 6th Aug 2021

Should You Learn TypeScript?

I have been putting writing this article off for a while now, but I thought it would be nice to share my thoughts on TypeScript as something that you might want to

 6th Aug 2021

Skills You Should Have Before Learning A JavaScript Framework

How much JavaScript should you know to move on to a framework? I get this question a lot from beginners in the field of web development. This article is just a