5 Must-Know JavaScript Array Methods You Should Know To Make Your Life Easier
Tags: javascript, beginners, codenewbie
Published: 2022-10-16 10:56:25

## Introduction

Arrays are great for storing related data and are often used as a way of organising information. Most of us use them on a daily basis, but did you know that there are also some really neat array methods built into JavaScript?

These methods make our lives much easier, optimising what would otherwise be multiple lines of code into one simple command. Whether you’re just getting started with arrays or already feel like an expert, this article will help you become more efficient when working with them.

## filter()
If you want to filter an array based on certain criteria, the filter() method might be what you need. This is a useful function that will return a new array with all the items you're interested in.

It requires a function as a parameter, which will be called for each element in the array. If the function returns true, that element will remain in the array; otherwise, it will be removed from the array.

### Example
We have requested data from the backend and would like to do client-side filtering based on a property that the array of objects has. In this case, we have requested jokes from JokeAPI and would like to filter the jokes where the category property equals Programming.

#### Code
```javascript
const response = {
    "error": false,
    "amount": 4,
    "jokes": [
        {
            "category": "Programming",
            "type": "single",
            "joke": "Judge: \"I sentence you to the maximum punishment...\"\nMe (thinking): \"Please be death, please be death...\"\nJudge: \"Learn Java!\"\nMe: \"Damn.\"",
            "id": 45,
            "safe": true,
            "lang": "en"
        },
        {
            "category": "Christmas",
            "type": "twopart",
            "setup": "How will Christmas dinner be different after Brexit?",
            "delivery": "No Brussels!",
            "id": 251,
            "safe": false,
            "lang": "en"
        },
        {
            "category": "Christmas",
            "type": "twopart",
            "setup": "What do Santa's little helpers learn at school?",
            "delivery": "The elf-abet!\n",
            "id": 248,
            "safe": true,
            "lang": "en"
        },
        {
            "category": "Christmas",
            "type": "twopart",
            "setup": "Why couldn't the skeleton go to the Christmas party?",
            "delivery": "Because he had no body to go with!",
            "id": 252,
            "safe": true,
            "lang": "en"
        }
    ]
}

const programmingJokes = response.jokes.filter((joke) => 
   joke.category === "Programming"
);

console.log("programmingJokes: ", programmingJokes);
```
#### Console output
```terminal
programmingJokes: [
  {
    "category": "Programming",
    "type": "single",
    "joke": "Judge: \"I sentence you to the maximum punishment...\"\nMe (thinking): \"Please be death, please be death...\"\nJudge: \"Learn Java!\"\nMe: \"Damn.\"",
    "id": 45,
    "safe": true,
    "lang": "en"
  },
]
```

Sandbox link - https://playcode.io/982694

## map()
The map() method transforms each item in an array, applying a function to it and storing the result in a new array, without actually changing the initial array.

### Example
We have requested data from the backend and would like to extract info from that data. In this case, we have requested random user data from RandomDataAPI and would like to extract each person's age into an array.

#### Code
```javascript
const response = [
  {
    "id": 7433,
    "uid": "4c2c1731-2c3c-4983-b39f-0f988791e98f",
    "password": "L903JpXGAj",
    "first_name": "Dalene",
    "last_name": "Kuhn",
    "username": "dalene.kuhn",
    "email": "dalene.kuhn@email.com",
    "avatar": "https://robohash.org/autmagnisunt.png?size=300x300&set=set1",
    "gender": "Agender",
    "phone_number": "+964 771-857-9446 x77784",
    "social_insurance_number": "607847845",
    "age": 25,
  },
  {
    "id": 3764,
    "uid": "0c1c9485-2b90-4e68-a795-0e4925aa8344",
    "password": "XjyI92Y1dl",
    "first_name": "Laurence",
    "last_name": "Lowe",
    "username": "laurence.lowe",
    "email": "laurence.lowe@email.com",
    "avatar": "https://robohash.org/quinonomnis.png?size=300x300&set=set1",
    "gender": "Agender",
    "phone_number": "+689 743-128-5476 x530",
    "social_insurance_number": "737935460",
    "age": 30,
  },
  {
    "id": 9408,
    "uid": "4933cb5d-f4f5-4bc3-8d37-f4c9b3129923",
    "password": "JrI8e4KVjs",
    "first_name": "Gabriella",
    "last_name": "Tillman",
    "username": "gabriella.tillman",
    "email": "gabriella.tillman@email.com",
    "avatar": "https://robohash.org/repellatmaioresmolestiae.png?size=300x300&set=set1",
    "gender": "Bigender",
    "phone_number": "+675 552-834-4168 x39534",
    "age": 21,
  }
]

const arrayOfAges = response.map(person => person.age);
console.log("arrayOfAges: ", arrayOfAges)
```
#### Console output
```terminal
arrayOfAges: [25, 30, 21]
```

Sandbox link - https://playcode.io/982843

## reduce()
The reduce() method reduces an array to a single value by applying a function on each element and accumulating the results. It's a great method for finding a total or for finding the average of all items.

### Example
We have an array that contains monthly deposits, and we would like to know the sum of all deposits.

#### Code
```javascript
const depositsArray = [
	{
		id: 1231,
		deposit: 5,
		currency: '$',
	},
	{
		id: 1231,
		deposit: 10,
		currency: '$',
	},
	{
		id: 1231,
		deposit: 20,
		currency: '$',
	},
	{
		id: 1231,
		deposit: 5,
		currency: '$',
	},
	{
		id: 1231,	
		deposit: 15,	
		currency: '$',
	},
];

  

const sumOfDeposits = depositsArray.reduce((total, transaction) => 
   total + transaction.deposit, 0
);
  
console.log('depositsArray: ', depositsArray);
console.log('sumOfDeposits: ', sumOfDeposits);
```
#### Console output
```terminal 
depositsArray: [{...}, {...}, {...}, {...}, {...}]
sumOfDeposits: 55
```

Sandbox link - https://playcode.io/982850

## some()
The some() method checks if at least one element in an array satisfies the test implemented by the provided function. If it does satisfy the test, it will return true; otherwise, it will return false.

### Example
We have requested users from a backend and would like to know if one of them has been flagged as a bot.
 
#### Code
```javascript
const response = [
  {
    id: 101,
    firstName: 'Muhammad',
    lastName: 'Ovi',
    age: 25,
    isBot: false,
  },
    {
    id: 102,
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    isBot: true,
  },
    {
    id: 103,
    firstName: 'Chris',
    lastName: 'Smith',
    age: 27,
    isBot: false,
  },
];

const isNotValidUsers = response.some((user) => user.isBot === false);

console.log("isNotValidUsers: ", isNotValidUsers)
```

#### Console output
```terminal
isNotValidUsers: true
```

Sandbox link - https://playcode.io/983403

## every()
The every() method checks if every element in the array satisfies the test implemented by the provided function. If it does, it will return true; otherwise, it will return false.

### Example
We have a list of products in our cart and would like to check whether or not there is stock.

#### Code
```javascript
const response = [
    {
      "id": 1,
      "title": "iPhone 9",
      "price": 549,
      "discountPercentage": 12.96,
      "rating": 4.69,
      "stock": 94
    },
    {
      "id": 2,
      "title": "Apple Watch",
      "price": 300,
      "discountPercentage": 10,
      "rating": 4.40,
      "stock": 20
    },
     {
      "id": 3,
      "title": "Apple Headphones",
      "price": 600,
      "discountPercentage": 7,
      "rating": 4.65,
      "stock": 2
    },
]

const hasStock = response.every((item) => item.stock > 0);

console.log("hasStock: ", hasStock);
```

#### Console output
```terminal
hasStock: true
```

Sandbox link - https://playcode.io/986629

## Conclusion
Arrays are one of the most basic and important data structures in any programming language. When learning JavaScript, it’s helpful to know how to use these array methods to manipulate and store data more efficiently. These methods include filter(), map(), reduce(), some(), and every() that can help make your code more efficient.