A JavaScript Array Method Cheat Sheet

Faba Technology
6 min readJan 24, 2024

--

Introduction

In programming, an array is a collection of elements, items, objects, etc. The array data structure is widely used in all programming languages as a basic element.

In this article, I would like to show you some secret methods for working with JavaScript arrays, and how you can dodge some array-related bugs.

Just your regular objects

In JavaScript, there are only 6 defined data types — the primitives (boolean, number, string, null, undefined) and object (the only reference type). Arrays do not belong to this list because they are objects as well. This is a common confusion among developers who assume that arrays are a special data type in JavaScript.

An array is an ordered list of values with the following characteristics:

  • holds values of mixed types, e.g. an array can store elements in number, string, and boolean type
  • is dynamic-sized and auto-growing, which means you don’t have to specify the array size upfront

Now let’s dive into our array method cheat sheet. Here is our code example:

Note: We will use DATA for all the following examples

{
"id": 1,
"first_name": "Emlen",
<br>
"last_name": "Crannis",
"email": "ecrannis0@blogs.com",
"gender": "Genderqueer",
"fee": 14
},
{
"id": 2,
"first_name": "Dasi",
"last_name": "Botwood",
"email": "dbotwood1@uiuc.edu",
"gender": "Female",
"fee": 15
},
{
"id": 3,
"first_name": "Risa",
"last_name": "Ginity",
"email": "rginity2@mapy.cz",
"gender": "Female",
"fee": 15
},
{
"id": 4,
"first_name": "Thorn",
"last_name": "Lorentzen",
"email": "tlorentzen3@linkedin.com",
"gender": "Male",
"fee": 9
},
{
"id": 5,
"first_name": "Anita",
"last_name": "Giacomuzzo",
"email": "agiacomuzzo4@digg.com",
"gender": "Female",
"fee": 20
}]

The array method cheat sheet

The some() method

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.

If we want to check the array has at least one element that passes the test function, we should use the some() method:

const hasLGBT = DATA.some((item) => item.gender !== 'Male' && item.gender !== 'Female')
// result: true

The every() method

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

If we want to check the array has all elements that passed our test function, we should use the every() method. Or we can use NOT with some. Let’s see the following example:

const hasFee = DATA.every((item) => item.fee > 0)
// result: true
// OR
const hasFee1 = !DATA.some((item) => item.fee <= 0)
// result: true

The find() method

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

From the some() method — we will check the array has an element that passes our test function, and if we want to get this element, we can use find():

const lgbtPerson = DATA.find((item) => item.gender !== 'Male' && item.gender !== 'Female')
// result: {
"id": 1,
"first_name": "Emlen",
"last_name": "Crannis",
"email": "ecrannis0@blogs.com",
"gender": "Genderqueer",
"fee": 14
}

The filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The find() method will get the first element it meets. So if we want to get all elements that pass our test function, we should use filter()

const femalePeople = DATA.filter((item) => item.gender === 'Female')
// result: [
{
"id": 2,
"first_name": "Dasi",
"last_name": "Botwood",
"email": "dbotwood1@uiuc.edu",
"gender": "Female",
"fee": 15
},
{
"id": 3,
"first_name": "Risa",
"last_name": "Ginity",
"email": "rginity2@mapy.cz",
"gender": "Female",
"fee": 15
},
{
"id": 5,
"first_name": "Anita",
"last_name": "Giacomuzzo",
"email": "agiacomuzzo4@digg.com",
"gender": "Female",
"fee": 20
}]

The map() method

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Sometime, we need to transform our array to another array with new value, or just add more fields into each object inside array. We should use map() to avoid modify the original array:

const newData = DATA.map((item) => {
return {
...item,
full_name: `${item.first_name} ${item.last_name}`
}
})
// result: [
{
"id": 1,
"first_name": "Emlen",
"last_name": "Crannis",
"email": "ecrannis0@blogs.com",
"gender": "Genderqueer",
"fee": 14,
"full_name": "Emlen Crannis"
},
{
"id": 2,
"first_name": "Dasi",
"last_name": "Botwood",
"email": "dbotwood1@uiuc.edu",
"gender": "Female",
"fee": 15,
"full_name": "Dasi Botwood"
},
{
"id": 3,
"first_name": "Risa",
"last_name": "Ginity",
"email": "rginity2@mapy.cz",
"gender": "Female",
"fee": 15,
"full_name": "Risa Ginity"
},
{
"id": 4,
"first_name": "Thorn",
"last_name": "Lorentzen",
"email": "tlorentzen3@linkedin.com",
"gender": "Male",
"fee": 9,
"full_name": "Thorn Lorentzen"
},
{
"id": 5,
"first_name": "Anita",
"last_name": "Giacomuzzo",
"email": "agiacomuzzo4@digg.com",
"gender": "Female",
"fee": 20,
"full_name": "Anita Giacomuzzo"
}
]

The reduce() method

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, to pass in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no “return value of the previous calculation”. If supplied, an initial value may be used in its place. Otherwise, the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of 0).

Instead of using for to loop each element and calculate with one variable, we can use reduce() and pass the calculation function to get the same result:

const totalFee = DATA.reduce((total, curValue) => total + curValue.fee, 0)
// result: 73

Bugs be at bay, array is here to save the day

Here are some of the array-based solutions you can implement to save yourself from potential code smells.

Use some() for better code clarity and code conciseness

const newData = DATA.map((item) => {
return item !== 'Male' && item !== 'Female'
})
if (newData.find((item) => item === true)) {
// has lgbt person
}

The code above works fine, however, we can use some() to handle this logic for better clarity. With just less than 3 lines of code, and the logic is clearer:

if (DATA.some((item) => item !== 'Male' && item !== 'Female')) {
// has lgbt person
}

Here is another code example:

const firstMatching = DATA.find((item) => item.fee > 0)
if (firstMatching) {
console.log('Bingo')
}

If we don’t use result from find(), or filter() and just want to check whether the array has our valid element, some() is a better option. The result will return in boolean (true OR false).

const hasValidElement = DATA.some((item) => item.fee > 0)
if (hasValidElement) {
console.log('Bingo')
}

Use map() to shorten the code

const ids = []
DATA.forEach((item) => {
ids.push(item.id)
})

In this case, we can use map() instead:

const ids = DATA.map((item) => item.id)

map() is similar to the forEach() as it executes the provided function once for each element in an array. But unlike the forEach() method, it creates a new array with the results of calling a function for every array element. In this case, we don’t need to define array ids first, all we need is to map from item to item.id with item.id is the data we want.

Closing

And that is it for our JS Array cheat sheet. We hope that this article has provided you with some more clarity on this subject. If you want to learn more about different functions, check out these two articles:

  1. The JavaScript Array Handbook — JS Array Methods Explained with Examples
  2. Array

On the topic of coding, if you are in need of offshore development firms capable of a cost-effective, high-quality, and comprehensive software solution, then look no further and reach out to us here.

--

--

Faba Technology

Collaborative, secure, and transparent Offshore Software Development