Arrays are used to store multiple values within a single variable. Arrays are usually used to store a list of elements that need to be accessed by a single variable.
I like to think of an array as an object that contains various other objects. For example, you could have an array called officeElements which would have elements like “chair”, “desk”, “door”, “computer”, etc.
In JavaScript an array can hold different elements which means you could store things like Strings, booleans, and numbers in the same array. In JavaScript arrays can be initialized in one of two ways, these ways are:
let myArray = [];
or
let myArray = array();
ECMAScript updates over the last couple of years have added a lot of new and very useful features to JavaScript. As part of these updates, there were a lot of new methods added to the array.
I believe that to use JavaScript effectively every developer should be able to use any one of these methods on an array. These methods can save a lot of lines of codes and also allow us to do some pretty awesome function programming!
- filter() – returns a sub array matching the condition
- forEach() – iterate every item
- some() – return Bool if some items match condition
- every() – return Bool if all items match condition
- includes() – return Bool if search present in an array
- map() – return a new array with your modification
- reduce() – return a single value using your operation
- sort() – returns the sorted array
- find() – returns value of first occurrence of the search
- findIndex() – returns index of first occurrence of the search
filter()
The filter() method returns a sub array of all elements that match the conditions.
For a really easy example, let’s say we wanted all of the customer’s purchases over $100. We would probably have code that looked something like this if we didn’t want to use filter or didn’t know about it yet! 🙂
const purchases = [{
'item': 'Camera',
'price': 500.00
}, {
'item': 'Apples',
'price': 5.00
}, {
'item': 'Pears',
'price': 3.95
}, {
'item': 'Tablet',
'price': 350
}, {
'item': 'Advil',
'price': 13.95
}, {
'item': 'Honey',
'price': 6.95
}]
let purchasesOver100 = []
for (let i = 0; i < purchases.length; i++) {
if (purchases[i].price > 100) {
purchasesOver100.push(purchases[i])
}
}
console.dir(purchasesOver100)
By using the filter method we can write a little bit less code and we can start chaining things together which allows us to do functional programming.
const purchases = [{
'item': 'Camera',
'price': 500.00
}, {
'item': 'Apples',
'price': 5.00
}, {
'item': 'Pears',
'price': 3.95
}, {
'item': 'Tablet',
'price': 350
}, {
'item': 'Advil',
'price': 13.95
}, {
'item': 'Honey',
'price': 6.95
}]
let purchasesOver100 = purchases.filter(p => p.price > 100);
console.dir(purchasesOver100)
As you can see, filter takes in a function as a parameter and then works on each element of the array and under the hood adds them to a new array. I love that it doesn’t mutate the original.
forEach()
The forEach method allows you to iterative through every item in the array. It’s really a good way of doing a for loop without having to declare variables and what not.
I think the big advantage of the forEach method is that it eliminates the chance of me having an off by one error every time I create a loop. Feels like every time I use a for loop I’m off by one!
const purchases = [{
'item': 'Camera',
'price': 500.00
}, {
'item': 'Apples',
'price': 5.00
}, {
'item': 'Honey',
'price': 6.95
}]
for (let i = 0; i < purchases.length; i++) {
doSomeTaxCalculation(purchases[i])
}
With forEach you can use fat arrow functions and don’t need to worry about what index you are working with because the execution environment looks after it. So the code from above could be modified a bit to look this:
const purchases = [{
'item': 'Camera',
'price': 500.00
}, {
'item': 'Apples',
'price': 5.00
}, {
'item': 'Honey',
'price': 6.95
}]
purchases.forEach(p => doSomeTaxCalculation(p))
some()
The some method tests that the array has at least one element that matches whatever the conditions in the function are. For example, let’s say you wanted to confirm that every customer was buying Apples and you had an array of fruit.
Without the some method you would need an additional variable that you would have to keep track of setting. It would look something like this:
const fruits = ['Pears', 'Apples', 'Oranges', 'Bananas', 'Strawberries']
let foundApples = false
for (let i = 0; i < fruits.length; i ++) {
if (fruits[i] === 'Apples') {
foundApples = true
}
}
if (foundApples) {
console.log('bought apples!')
}
With the use of the some method, we can write much simpler code.
const fruits = ['Pears', 'Apples', 'Oranges', 'Bananas', 'Strawberries']
if (fruits.some(fruit => fruit === 'Apples')) {
console.log('bought apples!')
}
The above code if it’s executed would print ‘bought apples!’ to the console.
every()
I don’t think I’ve ever used the every operator, but it seems like a really good way to enforce some validation! It feels like I would most likely use this to confirm that every element in the array had a value for certain properties.
includes()
The includes() method returns true if the array contains a matching element or false if it doesn’t.
Without the includes method we would probably write code something like this:
const pets = ['Cat', 'Dog', 'Fish', 'Snake']
let foundIt = false
for (let i = 0; i < pets.length; i++) {
if (pets[i] === 'Snake') {
foundIt = true
}
}
if (foundIt) {
console.log('Found the snake')
}
With the includes method we could really simplify our code to use a lot less variables and produce something like this:
const pets = ['Cat', 'Dog', 'Fish', 'Snake']
if (pets.includes('Snake')) {
console.log('Found the snake')
}
map()
The map method creates a new array that is the result of all elements passing through a passed in function. I find the map method to be useful when you need a specific value from an array of objects.
I often use this when I need the id numbers so I can query all of the records from the database.
reduce()
The reduce() methods turns an array into a single value. It’s great for calculating a total.
In the past, I’ve blogged about the JavaScript reduce() method check out my post “How to Use Reduce on JavaScript Arrays.”
sort()
There’s a lot of reasons why you may want to sort an array, often it is done to make things easier for the user of the application to understand the data.
In my blog post, How to Sort Arrays Alphabetically I’ve covered how to create a custom sort function.
find()
The find method returns the value of the first matching element in the array. If there’s no matching element it will return undefined, so you need to check for that.
If you’re going to do some sort of operation on it, you probably would want to on all matches so you might want to use filter instead. I haven’t used this much as I use includes, some, indexOf and filter a lot more frequently.
findIndex()
If you still need to support versions of Internet Explorer, findIndex is really useful. I’ve had to use it a lot in the past to see if an array contained a certain value.
I used to have a shim that I would add to the array actually that I called includes.
Wrapping Up
We’ve covered ten really great methods that can be used to really make your JavaScript code more brief and in a lot of cases make it a lot more functional.
I usually use map(), filter(), and reduce() methods in my day to day work. Occasionally, I might use some() or includes().