Calling all beginners - part I: fun with arrays!
Tags: beginners, javascript, tutorial
Published: 2022-07-11 09:27:40

_Cover photo by [Faris Mohammed](https://unsplash.com/@pkmfaris?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)_
___
  
Hello, coders! :computer:

In this series we're going to work with arrays as it is a concept beginners often struggle with.

## Language of choice
JavaScript seems to be quite popular on [dev.to](https://dev.to) so that's what I'll use.
If you'd like to see solutions in your language of choice don't hesitate to post a reply and hopefully someone will post a solution.

## About solutions shown here
Bear in mind that solutions are just _my_ take on exercises. There are various ways to implement a solution, some more optimized than others.
If you're reading this and want to offer an alternate solution you're more than welcome to do so in the comments! :speech_balloon:

## Exercise 1
You are given an array of user ages. Your task is to write code to calculate users' average age.


```javascript
const userAges = [12, 67, 45, 32, 71];

const averageAge = // your code here

console.log(`Average age is ${averageAge}`);
```

## Solution to exercise 1
{% details Click to view my solution %}
```javascript
const userAges = [12, 67, 45, 32, 71];

const getAverageAge = (ages) => {
    if (!Array.isArray(ages) || ages.length <= 0) {
        return 0; // or anything you see fit
    }

    return ages.reduce( (total, age) => total + age, 0) / ages.length;
}

const averageAge = getAverageAge(userAges);

console.log(`Average age is ${averageAge}`);
```
What's going on?

1. First we add a condition to make sure we are dealing with an array and that it's not empty.

1. Then we can use [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) to sum all ages.

1. We divide the result by the number of elements in the array. We can safely do that because we made sure the array was not empty, which means we're not dividing by zero.

{% enddetails %}

## Exercise 2
Now instead of an array of ages you start with an array of users.
Your task is the same: write code to calculate users' average age.


```javascript
const users = [            
    {id: 1, age: 12},
    {id: 2, age: 67},
    {id: 3, age: 45},
    {id: 4, age: 32},
    {id: 5, age: 71}
];

const averageAge = // your code here

console.log(`Average age is ${averageAge}`);
```

## Solution to exercise 2
{% details Click to view my solution %}
```javascript
const users = [            
    {id: 1, age: 12},
    {id: 2, age: 67},
    {id: 3, age: 45},
    {id: 4, age: 32},
    {id: 5, age: 71}
];

const getAverageAge = (ages) => {
    if (!Array.isArray(ages) || ages.length <= 0) {
        return 0; // or anything you see fit
    }

    return ages.reduce( (total, age) => total + age, 0) / ages.length;
}

const averageAge = getAverageAge(users.map(user => user.age));

console.log(`Average age is ${averageAge}`);
```
:confused: It looks almost the same as exercise 1! 

Developers are lazy so we reuse code whenever we can.
Our `getAverageAge` function of exercise 1 does the job so why not reuse it?
We _could_ but it needs an array of integers and we have an array of objects (`users`).
If we could create a new array with just the `age` property of each user then we'd be golden.
That's where [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Map) comes into play. We can use it to create a new array with each user's age:
```javascript
userAges.map(user => user.age)
```
and we pass that to `getAverageUser` and we're done!
{% enddetails %}

## Feedback
Let me know in the comments what you think of these kinds of short exercises and I'll try to come up with new ones as I think repetition is important to help understand concepts.

Happy coding! :keyboard: