Array functions in Javascript ES6


Let’s look at array functions today. One of the best features that the new javascript offers is the ability to work on lists of data in a few lines of code. We have them all, from mapping to searching or data aggregation.

Many of the functions used, in addition to being applied to the source array, will take an anonymous function as input as a parameter. In our case we will use arrow functions to be able to write less code: ES6 Javascript Arrow functions.
Furthermore, many of the functions do not modify the original array but return a new, modified one.

const outputArray = => { /* ...our code... */});

For our examples we will always use the same array to show how many ways an array can be managed, with little more than one instruction.

const people = [
  {name: "Harry", surname: "Potter", gender: "male", isMuggle: false, race: "human"},
  {name: "Ginny", surname: "Weasley", gender: "female", isMuggle: false, race: "human"},
  {name: "Hermione", surname: "Granger", gender: "female", isMuggle: false, race: "human"},
  {name: "Vernon", surname: "Dursley", gender: "male", isMuggle: true, race: "human"},
  {name: "Dobby", gender: "male", isMuggle: false, race: "elf"},
  {name: "Ron", surname: "Weasley", gender: "male", isMuggle: false, race: "human"},
  {name: "Petunia", surname: "Dursley", gender: "female", isMuggle: true, race: "human"}

Map array functions

The .map((item) => item) function allows you to transform lists of objects into lists of something else. We can do it by retrieving the information in an input list and extracting only the necessary information to send to the output. Let’s say we want to retrieve a list of names and surnames from a list of people.

In this case we will therefore have to recover the name, appending it to the surname and returning each element. The function that we will send as a parameter to map does just that: it retrieves each element and returns the transformed element.

const names = => `${}${i.lastname ? ' ' + i.lastname : ''}`);

// Result: ['Harry Potter', 'Ginny Weasley', 'Hermione Granger', 'Vernon Dursley', 'Dobby', 'Ron Weasley', 'Petunia Dursley']

Filter array functions

The function .filter((item) => boolean) allows to retrieve a sub-set of a larger set, based on some parameters established within the function, passed as a parameter. This function will then return another array with only the elements we decide.

Let’s take the example of wanting to retrieve only not magical beings from a list of magical and non-magical people. To achieve this we rely on those people having the boolean parameter of “muggle” set to true.

const mugglePeople = people.filter((i) => i.isMuggle);

/* Result: [{"name":"Vernon","lastname":"Dursley","gender":"male","isMuggle":true,"race":"human"},
{"name":"Petunia","lastname":"Dursley","gender":"female","isMuggle":true,"race":"human"}] */

Find functions

The function .find((item) => boolean) allows the search for an element of the list that has a parameter established in the passed function. While this function may look the same as the filter function, it has one big difference. The output of the find function will be the first element found with the requested characteristic and will not be an array, as is the case with filter. If, for example, we are going to look for several results with a certain characteristic in an array, the first one found will still be reported.

For example, we can search for a non-human creature within our people list.

const notHuman = people.find((i) => i.race !== 'human');

// Result: {name: 'Dobby', gender: 'male', isMuggle: false, race: 'elf'}

As a second example, just to better highlight the difference between filter and find, we report the same search query. We find at least one muggle within our array. The same occurrence will always be returned, the first within the array, as the arrays in javascript are indexed.

const mugglePeople = people.find((i) => i.isMuggle);

/* Result: {"name":"Vernon","lastname":"Dursley","gender":"male","isMuggle":true,"race":"human"} */

Reduce function

The function .reduce((accumulator, currentValue) => accumulator, initialValue) allows you to aggregate lists of data into a single value. In addition to the necessary parameters, it can also be determined what the initial value of the accumulator should be. Normally we will use the null value (0 in this case) in order not to distort the statistic.
We can use it for example to recover the percentage of female characters among the people.

const females = people.reduce((accumulator, currentValue) => currentValue?.gender === 'female' ? ++accumulator : accumulator, 0);
const femalesPerc = String((females * 100 / people.length) + '%');

// Result: 42.857142857142854%

Sort array functions

To sort an array we can use the following function:

['banana', 'strawberry', 'apple', 'pear'].sort();

For the sorting function I chose to create an ad hoc article. There are various possibilities that Javascript provides for sorting, from the simplest to some very complex ones. We can rely on the contents of the individual elements.

Here is the link to the article: Javascript custom array sorting functions.

Enqueue multiple array functions

The fact that the functions we have seen return a result allows us to queue multiple functions together. We can perform multiple transformations on the same array. This is also enqueuing everything, with as little redundancy as possible.

In this case, for example, we want both to recover the muggles (with filter()) and then only have their first and last names available (with map()).

const muggleNames = people.filter((i) => i.isMuggle)
    .map(i => `${}${i.lastname ? ' ' + i.lastname : ''}`);

// Result: ['Vernon Dursley', 'Petunia Dursley']

Please note: when queuing functions, the order is important! This is because what comes out of an array function is never the original array. It is a transformation or an element of it. Again citing the example given above, by inverting the filter and map functions we would have had an empty array as a result because the map function would have transformed the list into names and surnames only and the subsequent filter function would not have had the isMuggle property available for each element , on which to make logic.

// Not do this!
const muggleNames = => `${}${i.lastname ? ' ' + i.lastname : ''}`)
    .filter((i) => i.isMuggle);

// Result: []


Clearly we will never use all these functions at the same time but only one or two depending on what we need from the information lists.
Do you need a particular element of an array? Use the find function!
Do you need only a few elements of a larger set, with particular characteristics? Use the filter function!
Do you need to turn the entire list of items into a list of other items? The map function is the one for you!

That’s all for today, about array functions.
Try it at home!

Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.