Let's walk through the array methods I find more useful and that I use on a daily basis. Each of these methods has their own use case, and even though you can achieve the same results using a combination of a for
loop and a few auxiliary variables, understanding them and using them where appropriate will make your code a lot more readable and simpler.
forEach
The first one we'll talk about is the forEach
. This one resembles a for loop the most, but you can call it directly on a an array and have the each item of the array passed to the callback along with the current index. In other words, it will execute the provided function once for each element. For example:
['cat', 'dog', 'fish'].forEach((animal, index) => {
console.log([index, animal]);
})
// [0, 'cat']
// [1, 'dog']
// [2, 'fish']
You can also create the function to be executed, beforehand and pass it to the method (the same applies to all the other array methods:
function printIndexAndAnimal(index, animal) {
console.log([index, animal]);
}
['cat', 'dog', 'fish'].forEach((animal, index) => printIndexAndAnimal(index, animal))
Also useful to note is that the forEach
method (and all the other methods mentioned in this article) also passes the array itself as the third argument in the callback.
filter
This is a very handy method and I think I use it almost everyday. Like the name suggests, you can use it to filter an array, and it outputs another array with the elements that pass the test you provide in the callback function. For example, if you have an array of numbers, you can create another array with only the numbers that are greater than a threshold. Or if you have an array of objects that contain an id, you can create another array that does not contain an element with a specific id using filter. E.g.
const filteredArray = [1, 2, 3].filter(element => element > 1);
console.log(filteredArray)
// [2, 3]
const products = [
{ id: 1, name: 'Computer' },
{ id: 2, name: 'Pen' },
{ id: 3, name: 'Guitar' },
]
const filteredProducts = products.filter(product => product.id !== 2)
console.log(filteredProducts)
// [{ id: 1, name: 'Computer' }, { id: 3, name: 'Guitar' }]
find
You can use this method when you want to find one element in an array that satisfy a test function. This method will return either the first element that matches that test function otherwise it will return undefined
.
const products = [
{ id: 1, name: 'Computer' },
{ id: 2, name: 'Pen' },
{ id: 3, name: 'Guitar' },
]
const pen = products.find(product => product.id === 2)
console.log(pen)
// { id: 2, name: 'Pen' }
const cat = products.find(product => product.id === 'cat')
console.log(cat)
// undefined
some
This method returns either true or false if at least one element in the array matches a provided test function. It's useful when you want to make sure that at least one of the elements in the array satisfy a condition but you don't really want to manipulate that element or filter it out of the array:
function hasOneCat(element) {
return element === 'cat';
}
cosnt hasCat = ['fish', 'cat', 'dog'].some(animal => hasOneCat(animal))
console.log(hasCat)
// true
cosnt hasCat = ['fish', 'tiger', 'dog'].some(animal => hasOneCat(animal))
console.log(hasCat)
// false
every
This one behaves similarly to some
but in order to return true
, all elements in the array must satisfy the condition in the test function:
function isAboveFreezingCelsius(temperature) {
return temperature > 0;
}
cosnt allElementsAreAboveFreezing = [10, 2, 1, 3, 5, 100].every(temp => isAboveFreezingCelsius(temp))
console.log(allElementsAreAboveFreezing)
// true
cosnt hasCat = [0, 1, 8, 10, -1].every(temp => isAboveFreezingCelsius(temp))
console.log(allElementsAreAboveFreezing)
// false
map
This is another method I use almost everyday and it's very useful when you want to manipulate items in the array and return another array in which the function has been applied. One use case could be convert every element in an array to a different format and output that to a different variable without changing the original array:
function fromFahrenheitToCelsius(temperature) {
return (temperature - 32) / (9/5)
}
const converted = [212, 98.6, 32, 0, -40].map(temp => fromFahrenheitToCelsius(temp))
console.log(converted)
// [100, 37, 0, -17.78, -40]
reduce
Reduce is a little more complicated than the others. You can manipulate the array in a deeper level. I like to think of it as a mix of filter and map on the same method, but this can be used for so much more. You can use reduce to create another array with filtered and converted elements or you can even use it to reduce an array of numbers into a single result. When using reduce, not only you provide a function (called reducer) but you can also provide an initial value. Reduce's callback provides the current value in the itereation and an accumulator. The result of your function is assigned to the accumulator which carries on to the next iteration.
Let's start with a simple example, summing an array:
cosnt initialValue = 0;
cosnt result = [1, 2, 3, 4, 5].reduce((accumulator, currentValue) => {
accumulator += currentValue
return accumulator;
}, initialValue);
console.log(result);
// 15
Now, on to a more complex one. Let's split an array into two groups removing duplicates using reduce:
const originalArray = [2, 2, 43, 5, 11, 7, 9, 4, 20, 0, 4];
const initialValue = { lessThanTen: [], greaterThanTen };
function reducer(acc, value) {
if (acc.lessThanTen.includes(value) || acc.greaterThanTen.includes(value)) {
return acc;
}
if (value < 10) {
acc.lessThanTen.push(value);
} else {
acc.greaterThanTen.push(value);
}
return acc;
}
const result = originalArray.reduce((acc, value) => reducer(acc, value))
console.log(result)
// { lessThanTen: [2, 5, 7, 9, 4, 0], greaterThanTen: [43, 11, 20] }
I hope this article gave you a better idea of how all these methods work and after some practice you will have more tools on your belt and can help you improve your code's readability and performance. The best part about these methods is that besides the language syntax, the logic works the same in other languages, not only JavaScript :)
Top comments (0)