Coding / Programming Videos

Post your favorite coding videos and share them with others!

7 Javascript Array Methods – Leonardo Giroto – Medium

Source link

that every javascript dev should know and use! 🤓

I’m writing this article directed to Javascript developers who haven’t heard of one or any of those methods; beginners or not. They are better alternatives to using for loops and forEach loops in order to achieve specific tasks with Javascript Arrays; validating data or changing it.

Why use them?

  • Reduce the code complexity required to achieve specific goals;
  • Generally helps creating much more readable and clean code;
  • Minize side-effects by avoiding mutations on the original array.

Let’s get started!

We’ll use the array down below in order to demonstrate the usage of the presented methods. It is a simple array of objects, representing a list of guests attending a barbecue event.

const guests = [{
id: 1,
name: 'Ana Maria',
birthDate: new Date('1990-01-13'),
eatsMeat: true,
previousEventsAttended: 2
}, {
id: 2,
name: 'José Ricardo',
birthDate: new Date('1992-02-20'),
eatsMeat: false,
previousEventsAttended: 0
},{
id: 3,
name: 'Karina Faria',
birthDate: new Date('1991-05-01'),
eatsMeat: false,
previousEventsAttended: 3
}, {
id: 4,
name: 'Márcio Nunes',
birthDate: new Date('1993-08-12'),
eatsMeat: true,
previousEventsAttended: 1
},{
id: 5,
name: 'Nathália Viana',
birthDate: new Date('1994-10-08'),
eatsMeat: true,
previousEventsAttended: 0
}];

Validating and Retrieving Info

Some

By a given expression, it iterates through all the array itens checking for a match. It stops the iteration at the first truthy match and returns a boolean representing if any element match was found or not.

const hasVegetarians = guests.some((guest) => !guest.eatsMeat);

Since it is a barbecue, it is important to check if there are any vegetarians to guarantee that there will be food alternatives for them.

In the example above, we checked the guests array to see if any of the guests didn’t eat meat. Therefore, the returned value stored in hasVegans contains a boolean of value true, since there are guests who doesn’t eat meat.

Every

By a given expression, it iterates through all the array itens checking for a match. It stops the iteration at the first falsy match and returns a boolean representing if all the elements match or not.

const everyoneEatsMeat = guests.every((guest) => {
return guest.eatsMeat;
});

Above we are substantially checking the same as the previous example, but the approach here was different, we’re checking if everyone eats meat. The returned value stored in everyonEatsMeat contains a boolean of value false, since there are guests who doesn’t eat meat.

Find

By a given expression, it iterates through all the array itens checking for a match. It stops the iteration at the first match and returns the object/value representing the matching element in the array.

const searchTerm = 'Ana Maria';
const findAna = guests.find((guest) => {
return guest.name === searchTerm;
});

Suppose we have a search input for finding guests by their full name, in order to view their information on the screen.

We used find to check the array for a guest which the name is equivalent to the inputed value. Hence, the returned value stored in findAna contains the object from the array with all informations of Ana Maria.

FindIndex

By a given expression, it iterates through all the array itens checking for a match. It stops the iteration at the first match and returns the index of the matching element in the array.

const searchTerm = 'Ana Maria';
const findAnaIndex = guests.findIndex((guest) => {
return guest.name === searchTerm;
});

Above we are substantially checking the same as the previous example, but the returned value is different. Instead of the object from the array itself, the returned value stored in findAnaIndex contains its index in the array; 0.

Manipulating Arrays

Filter

It filters the original array, excluding the elements that does not match the given expression. The returned value is a new array containing only the elements that matched the expression.

const vegetarians = guests.filter((guest) => !guest.eatsMeat);

Now let’s say you need to send a message to the vegetarians guests informing the kind of alternative food there will be in the event.

In order to get a list of the vegetarian guests, we used filter to get a new array containing only those who does not eat meat. Therefore, the returned value stored in vegetarians contains an array of guests, contaning only those who doesn’t eat meat.

Map

It changes the original array, modifying all its elements to a new value/object according to the given expression. The returned value is a new array containing all the original elements transformed into a new value/object.

const guestsAges = guests.map((guest) => {
const diff = Date.now() - guest.birthDate.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);

});

The guests age are usually an important information for an event, but on the provided array we only have their birthdate.

In the example above, we generated a new array containing the age of each guest, by calculating it from their birthdate. The returned value stored in guestsAges is a number array containing all the guests ages.

Reduce

By iterating over the original array, it returns a single value based on the given expression. It builds up a value by repeated calling the iterator, passing in the previous values.

const agesSum = guestsAges.reduce((sum, guestAge) => {
return sum + guestAge
}, 0);
const avarageAge = agesSum / guestsAges.length;

For statistics purposes, it might be interesting to know the average age of the attending guests.

This one is a little bit trickier. The callback function receives two parameters: the current output and the current element in the iteration. Also, reduce requires another parameter, which is the initial value for the output.

Using reduce, we iterated through the array guestsAges (created in the previous example) summing the guests ages; initially setting the sum to 0. The returned value stored in agesSum is a sum of all the guests ages; (which is 132). By dividing it by the amount of guests, we get the average age: 26.4.

Summing It Up

Some > Returns a boolean value if the given expression is a match (true) for any of the array elements.

Every > Returns a boolean value if the given expression is a match (true) for all the array elements.

Find > Returns the first element that matches the given expression, or undefined if none matches.

FindIndex > The same and Find, but returns the element index in the array insted of the element itself.

Filter > Returns a new version of the array, filtered by the given expression.

Map > Returns a new version of the array, containing all original elements mapped to a different object/value.

Reduce > Returns a built up single value from a given expression by iterating over every array element.

Hope it helps! 😉

Source link

Bookmark(0)
 

Leave a Reply

Please Login to comment
  Subscribe  
Notify of
Translate »