Array cardio
Tags: javascript, beginners
Published: 2017-09-18 07:28:26

---
title: Array cardio
published: true
description: Playing with arrays
tags: JavaScript, beginners
cover_image: https://thepracticaldev.s3.amazonaws.com/i/fddj3aonfilqy5rbp1ru.jpg
---

> _Array cardio_ is an expression by [Wes Bos](https://dev.to/wesbos), 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.

```json
[
    {
        "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" ]
    }
]
```

Next I require the file inside my `index.js`.

```javascript
let datas = require('./datas.json')
```

Now, let's play!

## `array.push`

First, let's adding a new object to the array with [`array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a)
 
```javascript
datas.push(
    { 
        id: 6, 
        title: "Consectetur", 
        categories: [ "Dignissimos" ] 
    }
)
```

## `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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) is perfect for this job.

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

```

A `console.log` of `datasFilteredById` give us 

```javascript
[ { id: 5, title: 'Amet', categories: [ 'Culpa' ] } ]
```

## `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_<sup>__*__</sup> if `categories` property is `undefined`, if not, we use [`array.find`](https://developer.mozilla.org/en-US/search?q=array+find) to return object with the matching category found in `categories` property.

```javascript
const datasFilteredByCategory = datas.filter((obj) => {
	
	if (obj.categories === undefined) return
	
	return obj.categories.find((category) => {

		return category === 'Maxime';
	})
})
```

A `console.log` of `datasFilteredByCategory` give us 

```javascript
[ 
    { id: 3, title: 'Dolor', categories: [ 'Maxime', 'Animi' ] },
    { id: 7, title: 'Architecto', categories: [ 'Culpa', 'Maxime' ] },
    { id: 9, title: 'Libero', categories: [ 'Maxime', 'Elit', 'Neque' ] } 
]
```

## `array.map`

[`array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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`.

```javascript
const datasTitles = datas.map((data, index, array) => { return data.title })
```

A `console.log` of `datasTitles` give us

```javascript
[ 
    'Lorem',
    'Ipsum', 
    'Dolor', 
    'Sit', 
    'Amet', 
    'Architecto', 
    'Aliquam', 
    'Libero', 
    'Consectetur' 
]
```

## `array.sort`

Let's do the same thing again, but with ids sorted by increasing numbers. This is a job for [`array.sort`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/sort). `array.sort` compares each item in array.

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

	.sort((a, b) => { return a - b })
```

A `console.log` of `datasIds` give us:

```javascript
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
```

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`](https://developer.mozilla.org/en-US/search?q=array+reduce) and [spread syntax from ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). <small>_(To be honest, I'm not sure I fully understand this feature.)_</small> 

- Then we remove duplicates categories with `array.filter`.

```javascript
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 
    })
```

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

```javascript
[
    'Adipisicing',
    'Elit',
    'Maxime',
    'Animi',
    'Minima',
    'Culpa',
    'Neque',
    'Dignissimos'
]
```

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

What's your daily routine with arrays? ðŸƒðŸ»”â™€ï¸

---
<sup>__*__</sup><small>I don't know how to say that: _we return_? _We escape_? _We break_?</small>