Common JavaScript array methods

martinpersson

Martin Persson

Posted on July 25, 2020

Common JavaScript array methods

In this post we will look at some of the array methods in JavaScript. We start of with an array of users and se how we can use different array methods on them.

const users = [
  { name: 'Martin', age: 28 },
  { name: 'John', age: 60 },
  { name: 'Smith', age: 30 },
  { name: 'Jane', age: 22 },
  { name: 'Sarah', age: 55 },
  { name: 'Sam', age: 47 },
];
Enter fullscreen mode Exit fullscreen mode

1. map()

The Map method creates a new array based of the function we provide. In this example we want an array with all the users name.

const mappedUsers = users.map(user => {
  return user.name;
});

console.log(mappedUsers) // output: ['Martin', 'John', 'Smith', 'Jane', 'Sarah', 'Sam']
Enter fullscreen mode Exit fullscreen mode

2. forEach()

If we just want to console.log the name of the users without storing them in a new array we could use the forEach method. It will execute a provided function once for each element in the array.

users.forEach(user => {
  console.log(user.name) 
})
/* output:
 Martin
 John
 Smith
 Jane
 Sarah
 Sam
*/
Enter fullscreen mode Exit fullscreen mode

3. filter()

The filter method creates a new array based on the elements that pass a certain test or criteria. In this example we want to create a new array that contains all users above 40 years of age. We test each element and if they return true they are passed in to the new array.

const filteredUsers = users.filter(user => {
  return user.age > 40
})

console.log(filteredUsers) /* output:
 [ 
   { name: 'John', age: 60 },
   { name: 'Sarah', age: 55 },
   { name: 'Sam', age: 47 },
 ]
*/
Enter fullscreen mode Exit fullscreen mode

4. reduce()

In my opinion the reduce method is the hardest to understand. It is used to "reduce" an array to a single value. In this example we will combine it with the map method to calculate the avarage age of the users.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value. - Mozilla

Remember that the map method returns an array. So here we get the age of all users in an array and then we apply the reduce method on it, adding the accumulator and currentValue. Finally, to get the avarage we divide the number with the number of users.

const averageAge = users.map(user => user.age).reduce((a, c) => a + c) / users.length

console.log(averageAge) // output: 40.3
Enter fullscreen mode Exit fullscreen mode

5. slice()

The slice method returns a copy of a portion of the array into a new array. It takes two arguments, where to start copying and where to end (it does not include the end element). Here we want to copy Jane and Sarah to a new array. Jane is at index 3 and Sarah is at index 4, remember since the last element is not included, we have to “go past” Sarah to index 5.

const slicedUsers = users.slice(3, 5)

console.log(slicedUsers) /* output: 
 [
  { name: 'Jane', age: 22 },
  { name: 'Sarah', age: 35 },
 ]
*/
Enter fullscreen mode Exit fullscreen mode

6. splice()

The splice method changes the content of an array by removing elements. We can also choose to add a new element where we removed the element. This method alters the original array.

It takes 3 arguments, the first is at what index it will start, the second is how many elements it should remove. The last argument is optional, it is the new element if you want to add one.

In this example we want to remove Jane and Sarah from the array and replace them with Kate. Remember that splice does not return a new array so you will change the original.

users.splice(3, 2, {name: "Kate", age: 45})

console.log(users) /* output:
 [
   { name: 'Martin', age: 28 },
   { name: 'John', age: 60 },
   { name: 'Smith', age: 30 },
   { name: 'Kate', age: 45 },
   { name: 'Sam', age: 47 },
 ];
*/
Enter fullscreen mode Exit fullscreen mode

7. push()

The push method adds a new element at the end of the array. It is perfect if we want to add a new user to the array. We simply add the user as a parameter, we can add as many as we want but in this example we will only add one and that is Simon.

users.push({ name: 'Simon', age: 27 })

console.log(users) /* output:
 [
   { name: 'Martin', age: 28 },
   { name: 'John', age: 60 },
   { name: 'Smith', age: 30 },
   { name: 'Kate', age: 45 },
   { name: 'Sam', age: 47 },
   { name: 'Simon', age: 27 },
 ];
*/
Enter fullscreen mode Exit fullscreen mode

8. pop()

This method is straight forward. We remove the last element of the array, here we will remove Simon from the array.

users.pop()

console.log(users) /* output:
 [
   { name: 'Martin', age: 28 },
   { name: 'John', age: 60 },
   { name: 'Smith', age: 30 },
   { name: 'Kate', age: 45 },
   { name: 'Sam', age: 47 },
 ];
*/
Enter fullscreen mode Exit fullscreen mode

9. unshift()

This method is like the push method but instead of adding an element to the end of the array we add it to the beginning. This time we will add Simon to the beginning of the array.

users.unshift({ name: 'Simon', age: 27 })

console.log(users) /* output:
 [
   { name: 'Simon', age: 27 },
   { name: 'Martin', age: 28 },
   { name: 'John', age: 60 },
   { name: 'Smith', age: 30 },
   { name: 'Kate', age: 45 },
   { name: 'Sam', age: 47 },
 ];
*/
Enter fullscreen mode Exit fullscreen mode

10. shift()

Shift is similar to Pop, but this method removes the first element. So once again we will remove Simon from the array.

users.shift()

console.log(users) /* output:
 [
   { name: 'Martin', age: 28 },
   { name: 'John', age: 60 },
   { name: 'Smith', age: 30 },
   { name: 'Kate', age: 45 },
   { name: 'Sam', age: 47 },
 ];
*/
Enter fullscreen mode Exit fullscreen mode

If you want to learn more about all the JavaScript array methods you can look them up at the developer Mozilla webpage

💖 💪 🙅 🚩
martinpersson
Martin Persson

Posted on July 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related