DEV Community

Damien Sedgwick
Damien Sedgwick

Posted on

A Quick Look At Some Popular Array Methods In JavaScript

Today is going to be a quick look at some of the more popular array methods in JavaScript.

Each example will use the same set of data, an array of pet objects with different types of animal, their breed and their name.

So lets dive in.

Array.prototype.map()

.map() Creates a new array which is populated with the results of calling a provided function on every element in the calling array.

This is helpful for many reasons but in our example below, we have used .map() to create a new array to store all of our pet names in and we have stored them in a new variable names.

const pets = [
  {type: 'dog', name: 'Bruno', breed: 'Border Collie'},
  {type: 'cat', name: 'Bruce', breed: 'Maine Coon'},
  {type: 'dog', name: 'Tyson', breed: 'Bulldog'},
  {type: 'dog', name: 'Bobby', breed: 'English Bull Terrier'},
  {type: 'parrot', name: 'Paulie', breed: 'Macaw'}
];

const names = pets.map((pet) => pet.name);

console.log(names); // ['Bruno', 'Bruce', 'Tyson', 'Bobby', 'Paulie']
Enter fullscreen mode Exit fullscreen mode

Array.prototype.filter()

.filter() Creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

If we imagine that we have just fetched all of our pets from our database. .filter() is useful because in the scenerio where we only want to read the data of dogs, as in our example, it allows us to do exactly that. We can also store that data in a new variable such as dogs just as we have below.

const pets = [
  {type: 'dog', name: 'Bruno', breed: 'Border Collie'},
  {type: 'cat', name: 'Bruce', breed: 'Maine Coon'},
  {type: 'dog', name: 'Tyson', breed: 'Bulldog'},
  {type: 'dog', name: 'Bobby', breed: 'English Bull Terrier'},
  {type: 'parrot', name: 'Paulie', breed: 'Macaw'}
];

const dogs = pets.filter((pet) => pet.type === 'dog');

console.log(dogs); // [{type: 'dog', name: 'Bruno', breed: 'Border Collie'}, {type: 'dog', name: 'Tyson', breed: 'Bulldog'}, {type: 'dog', name: 'Bobby', breed: 'English Bull Terrier'}]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.forEach()

.forEach Executes a provided function once for each array element.

In our example below, our provided function is a rather trivial one that simply logs out a string to the console. However in a more real world situation (still using our pets), our function might return the last time a pet received a checkup (not currently in our data).

const pets = [
  {type: 'dog', name: 'Bruno', breed: 'Border Collie'},
  {type: 'cat', name: 'Bruce', breed: 'Maine Coon'},
  {type: 'dog', name: 'Tyson', breed: 'Bulldog'},
  {type: 'dog', name: 'Bobby', breed: 'English Bull Terrier'},
  {type: 'parrot', name: 'Paulie', breed: 'Macaw'}
];

function introducePet(pet) {
  console.log(`${pet.name} is a ${pet.breed} (${pet.type})`)
}

pets.forEach((pet) => introducePet(pet)); // Bruno is a Border Collie (dog)...
Enter fullscreen mode Exit fullscreen mode

Array.prototype.slice()

.slice() Also returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

In our example we are using .slice() to simply return the first element of array and store it in a new variable firstPet. We could also use it to return the first 3 or the last 3. The world is our oyster here.

const pets = [
  {type: 'dog', name: 'Bruno', breed: 'Border Collie'},
  {type: 'cat', name: 'Bruce', breed: 'Maine Coon'},
  {type: 'dog', name: 'Tyson', breed: 'Bulldog'},
  {type: 'dog', name: 'Bobby', breed: 'English Bull Terrier'},
  {type: 'parrot', name: 'Paulie', breed: 'Macaw'}
];

const firstPet = pets.slice(0, 1);

console.log(tyson); // [{type: 'dog', name: 'Bruno', breed: 'Border Collie'}]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.sort()

.sort() As the name suggests, sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

We may want to sort our data for various reasons, in our example we simply want to order our pets data alphabetically by their name.

It is worth noting that whilst the majority of array methods with create a new array or a shallow copy, .sort() will actually change the order of the array (mutation) so a handy trick if you want to prevent this from happening, is to use slice beforehand to create a copy of the original array order.

const pets = [
  {type: 'dog', name: 'Bruno', breed: 'Border Collie'},
  {type: 'cat', name: 'Bruce', breed: 'Maine Coon'},
  {type: 'dog', name: 'Tyson', breed: 'Bulldog'},
  {type: 'dog', name: 'Bobby', breed: 'English Bull Terrier'},
  {type: 'parrot', name: 'Paulie', breed: 'Macaw'}
];

pets.sort((a, b) => a.name.localeCompare(b.name)) // mutated array
pets.slice().sort((a, b) => a.name.localeCompare(b.name)) // copied array

console.log(pets); // [{ type: 'dog', name: 'Bobby', breed: 'English Bull Terrier' }, { type: 'cat', name: 'Bruce', breed: 'Maine Coon' }, { type: 'dog', name: 'Bruno', breed: 'Border Collie' }, { type: 'parrot', name: 'Paulie', breed: 'Macaw' }, { type: 'dog', name: 'Tyson', breed: 'Bulldog' }]
Enter fullscreen mode Exit fullscreen mode

That is it for this article and JavaScript array methods. I would highly recommend taking a look at MDN as there is a mountain of knowledge there, waiting to be digested. It is also where I got my array method descriptions from.

Top comments (0)