How to Use ES6 Array Methods to Loop Over An Array Collection

How to Use ES6 Array Methods to Loop Over An Array Collection

Simple Usage Guide

Do you remember something like this?

var text;

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

For those of you completely new to using JavaScript, let’s break down that code snippet.

  • All that statement is saying is that – “i is initially equals to zero. For as long as i is less than five, run the code inside the code block (i.e update the ‘text’ variable) and increment i by one (signified with the ++).

This used to be the standard way of looping through an array of items.

Used to.

EmcaScript 2016 (ES6) came with a set of utility methods for looping through an array. For those of you wondering, EmcaScript is a general-purpose programming language, standardised by Ecma International according to the document ECMA-262.

I like to think of EmcaScript as a new, modern and improved way of writing JavaScript.

These array iterators includes:

  • Array.map()
  • Array.find()
  • Array.filter()
  • Array.forEach()
  • Array.every()
  • Array.some()
  • Array.sort()
  • Array.reduce()

To properly understand how these methods work, we have to first understand two concepts:

  • The size of an array
  • The shape of an array

Consider this code:

const team = [
{
name: 'jack',
position: 'backend engineer'
},
{
name: 'lara',
position: 'ux designer'
},
{
name: 'kingsley',
position: 'developer'
},
{
name: 'mark',
position: 'manager'
},
{
name: 'chris',
position: 'developer'
}
]

There are two thing to note about this array:

  • It has a size of five items (objects),
  • Each item has a shape: a name and position.

With these in mind, all of the array iterator methods has it’s own behaviour:

  • map()

    • Behaviour: Changes the shape, but not the size,
    • Example: Get just the name of everyone on the team.
team.map((member) => {
return member.name; 
})
//Result: ['jack', 'lara', 'kingsley', 'mark', 'chris']

sort()

  • Behaviour: Changes neither the size nor the shape, but changes the order.
  • Example: Get the team members in alphabetical order.
team.sort();
//Result: [{name: 'chris', position: 'developer'}, {name: 'jack' ...}]

filter()

  • Behaviour: Changes the size, but not the shape.
  • Example: Get only the developers.
team.filter((member) => {
return member.position = “developer”; 
})

// [{name: 'kingsley', position: 'developer'}, {name: 'chris', position:'developer'}]

find()

  • Behavior: Changes the size to exactly one, but not the shape. It Does not return an array.
  • Example: Get the manager.
team.find((member) => {
return member.position = manager; 
})

// Result: {name: 'justin', position: 'manager'}

N/B: If there were two managers present, find() will only return the first

forEach()

  • Behaviour: Uses the shape, but returns nothing.
  • Example: Give all members a bonus!
Function sendBonus(member) {
    //code for bonus goes here\
}

team.forEach((member) => {
sendBonus(member); 
})

//Result: Jack gets a bonus! Lara get a bonus!… (but no return value).

reduce()

  • Action: Changes the size and the shape to pretty much anything you want.
  • Example: Get the unique team positions.
const uniquePos = team.reduce((uniquePos, member) => {
 if (uniquePos.includes(member.position)) {
 return uniquePos;
 }
 return [...uniquePos, member.position];
 }, []);
// Result: [‘backend engineer’, ‘ux designer’, ‘developer’, ‘manager’]

A bit confused, let’s break down this code guys.

  • The essence of this all is to get every unique position of each member. Duplicate positions (developer) will be picked once.

  • The first parameter taken by the reduce method is the ‘collectedValue’ from the last iteration. When the iteration is just starting, then the reduce() second argument ([] in our case) will be used. For every iteration, the collected or total value is added the current item.

  • In our case, when iteration just starts, the initial value [] wraps the current item in the array.

  • The conditional checks to see if the total value (the array at this point in the loop) includes the position of the current member. If it does, the position is ignored and the CollectedValue is returned as it was. If not, the position of the current member is added to the array (with the spread operator).

every()

  • Behavior: Changes neither the size nor the shape. Returns a Boolean: true if all items meet a condition, false if any doesn’t.
  • Example: Check if all items are objects.
team.every((member) => {
return typeof member = object;
})

// Results: True

some()

  • Behavior: Changes neither the size nor the shape. Returns a Boolean: true if any of the items meet a condition, false if all doesn’t.
  • Example: Check if any of the items is number.
team.some((member) => {
return typeof member = number;
})

// Result: False

That’s it. I hope you learnt something from this friends. If you did, consider subscribing to this blog.

I will really appreciate it.

Thank you and see you soon.

 
Share this