Useful JavaScript Arrays Methods
Tags: javascript, tutorial, webdev, beginners
Published: 2021-03-03 09:59:02

Originally posted on [bigsondev.com](https://bigsondev.com/blog/arrays-and-how-to-avoid-loops/)

---

*Arrays exist in every programming language. It's a data structure best suited for storing multiple values. And, for doing various operations on these values, often called as a collection.*

---

# Introduction
It's always best to learn by doing. Take a look at the below code example, study, and execute it step by step.

```javascript
// Create an array of 3 items using [ ] brackets
const friends = ["John", "Joe", "Jane"];
​
// Here we have a "collection" of friends declared as an array
console.log(friends); // ["John", "Joe", "Jane"]
​
// Array is indexed from 0 and not from 1
// 0 -> "John", 1 -> "Joe", 2 -> "Jane"
​
// Access particular friend from an array
console.log(friends[0]); // "John"
console.log(friends[1]); // "Joe"
console.log(friends[2]); // "Jane"
console.log(friends[3]); // undefined (we don't have 4th item)
​
// Get length of the array
console.log(friends.length); // 3 (as we have 3 items in the friends array)
​
// Safe way to get the last item of an array 
console.log(friends[friends.length - 1]) // "Jane"
​
// Directly change an array item
friends[0] = 'Pedro';
console.log(friends); // ["Pedro", "Joe", "Jane"]
​
// Directly push to an array
friends.push('Max');
console.log(friends); // ["Pedro", "Joe", "Jane", "Max"]
​
// Directly remove the item from an array
friends.pop();
console.log(friends); // ["Pedro", "Joe", "Jane"]
```

Let's learn how to utilize array methods to do useful operations on the entire collection.

---

## Useful Array Methods & Avoiding Loops
Changing original array items, pushing to it results in mutating which can introduce unwanted, side effects and makes code much more difficult to maintain. Let's aim for a declarative, functional approach with immutability in mind. Go through the below examples to see how we can easily achieve that with less code and more semantics.

### 1. [.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)

**Assignment**: Multiply all numbers by 2.

Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
​
for (let i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i] * 2;
}
​
console.log(numbers); // [10, 20, 30, 40]
```

Map numbers in an array:
```javascript
const numbers = [5, 10, 15, 20];
const multipliedNumbers = numbers.map((number) => number * 2);
​
console.log(numbers); // [5, 10, 15, 20];
console.log(multipliedNumbers); // [10, 20, 30, 40]
```

### 2. [.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

**Assignment**: Remove all numbers less or equal to 10.

Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
const filteredNumbers = [];
​
for (let i = 0; i < numbers.length; i++) {
  const currentNumber = numbers[i];
   
  if (currentNumber > 10) {
    filteredNumbers.push(currentNumber);
  } 
}
​
console.log(numbers); // [5, 10, 15, 20]
console.log(filteredNumbers); // [15, 20]
```

Filter numbers in an array:
```javascript
const numbers = [5, 10, 15, 20];
const filteredNumbers = numbers.filter((number) => number > 10);
​
console.log(numbers); // [5, 10, 15, 20]
console.log(filteredNumbers); // [15, 20]
```

### 3. [.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)

**Assignment**: Sum all numbers.

Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
let sum = 0;
​
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}
​
console.log(sum); // 50
```

Reduce numbers to create a sum:
```javascript
const numbers = [5, 10, 15, 20];
const sum = numbers.reduce((accumulator, number) => accumulator += number, 0);
​
console.log(sum); // 50
```

### 4. [.indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)

**Assignment**: Find an index of number 15.

Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
const numberToFind = 15;
let numberToFindIndex = undefined;
​
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === numberToFind) {
    numberToFindIndex = i;
    break;
  }
}
​
console.log(numberToFindIndex); // 2, remember that array is indexed from 0
```

Find index by using an indexOf method::
```javascript
const numbers = [5, 10, 15, 20];
const numberToFind = 15;
const numberToFindIndex = numbers.indexOf(numberToFind);
​
console.log(numberToFindIndex); // 2, remember that array is indexed from 0
```

### 5. [.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)

**Assignment**: Check if all numbers are greater or equal to 10.

Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
const minimumValue = 10;
let isBigEnough = true;
​
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] < minimumValue) {
    isBigEnough = false;
    break;
  }
}
​
console.log(isBigEnough); // false
```

Check if condition is true to all numbers::
```javascript
const numbers = [5, 10, 15, 20];
const minimumValue = 10;
const isBigEnough = numbers.every((number) => number >= minimumValue);
​
console.log(isBigEnough); // false
```

### 6. [.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)

**Assignment**: Check if any number is greater or equal to 10.

Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
const minimumValue = 10;
let isBigEnough = false;
​
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] >= minimumValue) {
    isBigEnough = true;
    break;
  }
}
​
console.log(isBigEnough); // true
```

Check if condition is true to any number::
```javascript
const numbers = [5, 10, 15, 20];
const minimumValue = 10;
const isBigEnough = numbers.some((number) => number >= minimumValue);
​
console.log(isBigEnough); // true
```

### 7. [.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)

**Assignment**: Check if number 15 is included in the numbers array.
Loop solution:
```javascript
const numbers = [5, 10, 15, 20];
const numberToFind = 15;
let isNumberIncluded = false;
​
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === numberToFind) {
  isNumberIncluded = true;
  break;
  }
}
​
console.log(isNumberIncluded); // true
```

Check if number is included:
```javascript
const numbers = [5, 10, 15, 20];
const numberToFind = 15;
const isNumberIncluded = numbers.includes(numberToFind);
​
console.log(isNumberIncluded); // true
```

---

# Bonus
I described couple of more methods, techniques to work with arrays, example below:

```javascript
const myAnimals = ['dog', 'cat'];
const myFriendAnimals = ['bird', 'python', 'elephant'];
// Cool way to join arrays together using spread operator
const ourAnimals = [...myAnimals, ...myFriendAnimals];
​
console.log(ourAnimals); // ["dog", "cat", "bird", "python", "elephant"]
​
// Cool way to fill in array from something using .from method
const numbers = Array.from({ length: 10 }, (_, key) => key);
​
console.log(numbers); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
​
const nestedArray = [[1, 2], [3, 4], [5, 6]];
// Cool way to flatten an array using .flat method
const flatArray = nestedArray.flat();
​
console.log(flatArray); // [1, 2, 3, 4, 5, 6]
```

---

# Summary
I have lots of fun with immutability and enjoy it to the max. Don't remember when I wrote a loop last time. Mostly working on Frontend tho, might be totally different when working with Backend as it's all about optimizations then. Find your balance.

Declarative, functional programming is cool but there is nothing wrong with mutations too. Using break or loops might be necessary, don't limit yourself to one style. It's all about conventions when working in a team and if you mostly work solo, find what suits you the best.

There are [more array methods](https://www.w3schools.com/js/js_arrays.asp) in JavaScript, but I mostly focused on the ones which avoid mutations. I hope you learned something along the way.

---
I'm thinking about creating YT video series - building [projects](https://bigsondev.com/projects/) from my website, step-by-step, modern technologies, best coding practices with a thorough explanation.

If you enjoy the content and like the idea, [Buy me a pizza](https://www.buymeacoffee.com/bigsondev).
Let's reach that goal together. 😊

Thanks for all the support!

Get in touch: [Mentorship](https://bigsondev.com/mentorship/) | [Twitter](https://twitter.com/BigsonDev) | [LinkedIn](https://www.linkedin.com/in/adrian-bigaj-282277130/)