Arrays are wonderful and a very particular type in JavaScript. There are many useful built-in properties and methods that will help you resolve any task which involves arrays. Today we are going to discuss 15 array methods every developer should know.
Notice the list is not enumerated as I don’t believe one method is more important than the other, each of them will resolve a different problem, and thus is important we are familiar with all.
The some()
tests whether at least one element in the array passes the test implemented by the callback
function. The callback
function will receive 3 arguments, the item, the index, and the full array. Additionally, is possible to assign a value for this
when executing the callback
by using the argument thisArg
.
Definition:
arr.some(callback(element[, index[, array]])[, thisArg])
Examples:
const a = [1, 2, 3, 5, 8].some(item => item > 5)
const b = [1, 2, 3, 4, 5].some(item => item > 5)
console.log(a)
console.log(b)
---------
Output
---------
> true
> false
The every()
method is in a way similar to the some()
method, but it tests whether all the elements in the array pass the test implemented by the callback
function.
Definition:
arr.every(callback(element[, index[, array]])[, thisArg])
Examples:
const a = [10, 9, 8, 7, 6].every(item => item > 5)
const b = [7, 6, 5].every(item => item > 5)
console.log(a)
console.log(b)
---------
Output
---------
> true
> false
The reduce()
method executes a callback
function once for each assigned value present in the array, taking 4 arguments:
The first time the callback
is called, accumulator
and currentValue
can be either the initialValue
if provided, and the first value in the array if not.
Definition:
arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
Let’s see with an example how reduce()
works:
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue)
If we go step by step and put in a table all the parameters plus the resulting value of the callback
, we would get the following:
And the final result would be 10
. In our particular case I did not provide an initial value, let’s try that next
const initialValue = 10
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue, initialValue)
With this new scenario our table would like:
And the final resulting value is 20
.
The reduce()
function is great and it has several uses like sum all the values of an array or in an object array, counting for particular items in the array, grouping objects, merging arrays contained in array of objects, removing duplicates, etc.
#arrays #java #code #javascript