Array cardio

19h47

Jérémy Levron

Posted on September 18, 2017

Array cardio

Array cardio is an expression by Wes Bos, I learn a lot from him. ✌️

In my opinion arrays in JavaScript are the key of the language. So I practice, again and again, to really understand it, and avoid ugly loops when I fetch arrays.

So let's go!

First I created a JSON file with dummy datas inside. We keep it simple, but we already have a lot to play.

[
    {
        "id": 1,
        "title": "Lorem",
        "categories": [ "Adipisicing", "Elit" ]
    },
    {
        "id": 2,    
        "title": "Ipsum",
        "categories": [ "Elit" ]
    },
    {
        "id": 3,
        "title": "Dolor",
        "categories": [ "Maxime", "Animi" ]
    },
    {
        "id": 4,
        "title": "Sit",
        "categories": [ "Minima" ]
    },
    {
        "id": 5,
        "title": "Amet",
        "categories": [ "Culpa" ]
    },
    {
        "id": 7,
        "title": "Architecto",
        "categories": [ "Culpa", "Maxime" ]
    },
    {
        "id": 8,
        "title": "Aliquam"
    },
    {
        "id": 9,
        "title": "Libero",
        "categories": [ "Maxime" , "Elit", "Neque" ]
    }
]
Enter fullscreen mode Exit fullscreen mode

Next I require the file inside my index.js.

let datas = require('./datas.json')
Enter fullscreen mode Exit fullscreen mode

Now, let's play!

array.push

First, let's adding a new object to the array with array.push

datas.push(
    { 
        id: 6, 
        title: "Consectetur", 
        categories: [ "Dignissimos" ] 
    }
)
Enter fullscreen mode Exit fullscreen mode

array.filter

Now, we are going to filter datas by a given id integer and stock the result in a new array. This way, the original array doesn't change.

array.filter is perfect for this job.

const datasFilteredById = datas.filter((obj) => {
    return obj.id === 5
})

Enter fullscreen mode Exit fullscreen mode

A console.log of datasFilteredById give us

[ { id: 5, title: 'Amet', categories: [ 'Culpa' ] } ]
Enter fullscreen mode Exit fullscreen mode

array.find

We are gonna do the same thing but with categories: filter datas by a given category string.

But, where id property is only integer, categories are lists. And in addition categories property maybe doesn't exist.

Let's do this. We return* if categories property is undefined, if not, we use array.find to return object with the matching category found in categories property.

const datasFilteredByCategory = datas.filter((obj) => {

    if (obj.categories === undefined) return

    return obj.categories.find((category) => {

        return category === 'Maxime';
    })
})
Enter fullscreen mode Exit fullscreen mode

A console.log of datasFilteredByCategory give us

[ 
    { id: 3, title: 'Dolor', categories: [ 'Maxime', 'Animi' ] },
    { id: 7, title: 'Architecto', categories: [ 'Culpa', 'Maxime' ] },
    { id: 9, title: 'Libero', categories: [ 'Maxime', 'Elit', 'Neque' ] } 
]
Enter fullscreen mode Exit fullscreen mode

array.map

array.map create a new array by calling a function on every item of a given array.

Here we just retrieve the title property of every objects and storing them into datasTitles.

const datasTitles = datas.map((data, index, array) => { return data.title })
Enter fullscreen mode Exit fullscreen mode

A console.log of datasTitles give us

[ 
    'Lorem',
    'Ipsum', 
    'Dolor', 
    'Sit', 
    'Amet', 
    'Architecto', 
    'Aliquam', 
    'Libero', 
    'Consectetur' 
]
Enter fullscreen mode Exit fullscreen mode

array.sort

Let's do the same thing again, but with ids sorted by increasing numbers. This is a job for array.sort. array.sort compares each item in array.

const datasIds = datas
    .map((data, index, array) => { return data.id })

    .sort((a, b) => { return a - b })
Enter fullscreen mode Exit fullscreen mode

A console.log of datasIds give us:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Enter fullscreen mode Exit fullscreen mode

Everything is fine for now.

array.reduce and Spread syntax

Finally, the more trickiest in my opinion. We are gonna create a list of each category used by datas.

  • First we have to check for categories property existence with array.filter.

  • Then we create an array with all existing categories properties with array.map.

  • We concat this new array, because it's an array of arrays, with array.reduce and spread syntax from ES6. (To be honest, I'm not sure I fully understand this feature.)

  • Then we remove duplicates categories with array.filter.

const datasCategories = datas

    .filter((obj) => { 

        return obj.categories !== undefined ? obj : '' 
    })

    .map((data, index, array) => { return data.categories })

    .reduce((a, b) => { return [...a, ...b] })

    .filter((category, index, array) => { 

        return array.indexOf(category) === index 
    })
Enter fullscreen mode Exit fullscreen mode

Sure there is a much simpler way to do this, but it's working. A console.log of datasCategories to confirm it:

[
    'Adipisicing',
    'Elit',
    'Maxime',
    'Animi',
    'Minima',
    'Culpa',
    'Neque',
    'Dignissimos'
]
Enter fullscreen mode Exit fullscreen mode

Maybe I'm doing it wrong, and I would love to have feedbacks, corrections or best practices.

What's your daily routine with arrays? 🏃🏻”♀️


*I don't know how to say that: we return? We escape? We break?

💖 💪 🙅 🚩
19h47
Jérémy Levron

Posted on September 18, 2017

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

Sign up to receive the latest update from our blog.

Related