Advanced Array Methods In JavaScript.

Emmanuel Madu IP
7 min readAug 20, 2020
Google images

In this article, I’m only focusing on advanced array methods assuming you already know what an array Is, for better understanding of an Array, visit the link https://en.wikipedia.org/wiki/Array_data_structure.

In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula.

As you start getting comfortable with JavaScript functions like Higher Order functions, callback functions, and loops, the next step is to learn about some of the useful methods in JavaScript that can help reduce code duplication.

We are going to learn methods like — forEach(), map(), filter(), some(), every(), and reduce().

These allow us to perform any form of operations we like on Array.

#1. forEach() Method

forEach is invoked on an array, it iterates or loops through the array and runs a Callback function on each value in the array and when the loop ends forEach returns undefined.

If you try to store the value of a forEach in a variable or return the value of a forEach in a function, you will still always get undefined.

ALWAYS, ALWAYS REMEMBER forEach() RETURNS UNDEFINED.
Inside the callback function of the forEach() method, we can get access to each value, the index of the value, and the array itself. As we can see in the diagram below which show the anatomy of the forEach() method.

courtesy of Ellie at advanced bootcamp by colt steele
Courtesy of Ellie at Advanced Web Development Bootcamp by Colt Steele

From the diagram above, we started with an array and invoked the array method on it, which is forEach, we now passed our callback function. The callback function accepts three(3) parameters; the first is each value in the array, the second is the index that we add the array, the third is the entire array.

Inside of the callback function, we place code that we would like to be run for each value in the array since there are three(3) values in the array, the callback function will run three(3) times.

Note: We can call the parameters to the callback whatever we want, also we do not always need all three parameters, use whichever ones you need, just remember the order is important!

How forEach works behind the scene!

//If run the code below in your browser console, it will output 'undefined' as the value.function forEach(array, callback){
for(var i = 0; i < array.length; i++){
callback(array[i], i, array)
}
}
// undefined

Remember, functions that don’t have a ‘return’ keyword will always output ‘undefined’ as the value.

Example of forEach() method

var arr = [1,2,3,]
arr.forEach(function(value, index, array){
console.log(value, index, array)
})
// 1 0 [1, 2, 3]
// 2 1 [1, 2, 3]
// 3 2 [1, 2, 3]
// undefined

Using forEach() in a function

function halfValues(arr){
var newArr = [];
arr.forEach(function(val){
newArr.push(val / 2)
})
return newArr;
}
halfValues([2,4,6]);// [1, 2, 3]

#2. map() Method

It’s very common to transform one array into an array with different values, or you can make a new array and use forEach() to push values into the new array. There’s an easier way to do that using map().

map() is invoked on an array and it creates a new array, it iterates over the array it’s called on and runs a callback function for each value in the array, it takes the value returned from the callback function and places it in the new array and when it’s done iterating it returns the new array.

Always remember map() returns a new array of the same length.

How map() works behind the scene!

function map(arr, callback){
var newArr = []
for(var i = 0; i < arr.length; i++){
newArr.push(callback(arr[i], i, arr))
}
return newArr;
}
// undefined

Example of a map() method

var arr = [1, 2, 3]arr.map(function(value, index, array){
return value * 2
});
// [2, 4, 6]

Using map() in a function

function trippleValues(arr){
return arr.map(function(value){
return value * 3
});
}
trippleValues([1, 2, 3]);
// [3, 6, 9]

The reason why we used map() instead of forEach() is because map() method is a bit more friendly than forEach() since it already returns a new array to us, while forEach can be used if you want to override the value in an array.

Another map() method example

function onlyFirstName(arr){
return arr.map(function(val){
return val.firstname
})
}
onlyFirstName([{firstname: 'Emmanuel', lastname: 'Madu'}, {firstname: 'Ifeanyichukwu', lastname: 'Paul'}]// ["Emmanuel", "Ifenayichukwu"]

#3. filter() Method

Just like forEach() and map(), filter() accepts a callback function and it’s invoked on arrays but the callback function is a little different from the one’s we used in the previous methods because the result of the callback function will always be evaluated into a Boolean.

It creates a new array, iterates through an array, runs a callback function on each value in the array, if the callback function returns true, that value will be added to the new array, but if the callback function returns false, that value will be ignored from the new array.

The result of the callback will ALWAYS be a BOOLEAN

How filter() works behind the scene!

function filter(array, callback){
var newArr = [];
for(var i = 0; i < array.length; i++){
if(callback(array[i], i, array)){
newArr.push(array[i])
}
}
}
// undefined

An example of a filter() method

var arr = [1, 2, 3,];
arr.filter(function(value, index, array) {
// no need for an if statement
// just return an expression that evalueate TRUE or FALSE
return value > 2
})
// [3]

Note: We can call the parameters to the callback whatever we want, also we do not always need all three parameters, use whichever ones you need, just remember the order is important!s

Another filter() example

var instructors = [{name: 'Joe'}, {name: 'Mary'}, {name: 'Godfrey'}, {name: 'Immaculate'}]instructors.filter(function(value, index, array){
return value.name.length > 3
});
// [{name: "Mary"}, {name: "Godfrey"}, {name: "Immaculate"}]

Using filter() in a function

function onlyFiveLetterNames(arr){
return arr.filter(function(value){
return value.length === 5
})
}
onlyFiveLetterNames(['River', 'Ocean', 'Sea', 'Spring', 'Water'])// ["River", "Ocean", "Water"]

#4. some() Method

It Iterates through an array, runs a callback function on each value in the array if the callback returns true for at least one single value it returns true, otherwise, it returns false.

The idea here is that if some of the values passed to the callback returns true, the entire functions return true. Just like the filter()method, the results of the callback will ALWAYS be a BOOLEAN.

How some() works behind the scene!

function some(array, callback){
for(var i = 0; i < array.length; i++){
if(callback(array[i], i, array)){
return true
}
}
return false
}

Example of some() method

var arr = [1, 2, 3,];
arr.some(function(value, index, array){
return value < 2
})
// truevar arr = [1, 2, 3,];
arr.some(function(value, index, array){
return value > 4
})
// false

Using some() in a function

function hasEvenNumbber(arr){
return arr.some(function(value){
return value % 2 === 0
})
}
hasEvenNumbber([1, 2, 3, 4]) // truehasEvenNumbber([1, 3, 5]) // false

#5. every() Method

It iterates through an array, runs a callback function on each value in the array, however, if the callback function returns false for any singe value, the entire every function returns false.

The idea here is, in order for every to return true, every single value that will iterate over has to return true to the callback function.
The results of the callback will ALWAYS be a BOOLEAN.

How every() works behind the scene!

function some(array, callback){
for(var i = 0; i < array.length; i++){
if(callback(array[i], i, array)=== false){
return false
}
}
return true
}

Example of every() method

var arr = [-1, -2, -3]
arr.every(function(value, index, array) {
return value < 0
})
// true

Using every() in a function

function allLowerCase(str){
return str.split(' ').every(function(value){
return value === value.toLowerCase()
})
}
allLowerCase('kelvin is badass developer') // trueallLowerCase('kelvin is badass Developer') // false

#6. reduce() Method

The idea behind reduce() is that we can take an array and turn it into another data structure, that could be a string, a number, an object an array of arrays, etc. It accepts a callback function and an optional second parameter, it iterates through an array and runs a callback function on each value in the array.
The first parameter to the callback is either the first value in the array or the optional second parameter that reduce() accepts. This first parameter to the callback is commonly called the ‘accumulator’.
Finally, the returned value from the callback becomes the new value of the accumulator.
The diagram below describes the anatomy of reduce

Courtesy of Ellie at Advanced Web Development Bootcamp by Colt Steele

The diagram below breaks down how reduce works!

Courtesy of Ellie at Advanced Web Development Bootcamp by Colt Steele

Adding the second parameter

Courtesy of Ellie at Advanced Web Development Bootcamp by Colt Steele

How reduce() method work with strings

Courtesy of Ellie at Advanced Web Development Bootcamp by Colt Steele

How reduce() method work with objects

Courtesy of Ellie at Advanced Web Development Bootcamp by Colt Steele

Using reduce() in a function

function sumoddNumbers(arr){
return arr.reduce(function(accumulator, nextValue){
if(nextValue % 2 !== 0){
accumulator += nextValue
}
return accumulator;
}, 0)
}
sumoddNumbers([1, 2, 3, 4, 5])
// 9
//another examplefunction createFullName(arr){
return arr.reduce(function(accumulator, nextValue){
accumulator.push(nextValue.first + " " + nextValue.last);
return accumulator;
}, []);
}
createFullName([{first: 'Emmanuel', last: 'Madu'}, {first: 'Ifeanyichukwu', last: 'Paul'}])// ["Emmanuel Madu", "Ifeanyichukwu Paul"]

The materials covered are the foundation for understanding more complex Javascript libraries and frameworks like React also for functional programming.

--

--

Emmanuel Madu IP

Aspiring Software Engineer | Trying to New Things Learn Everyday | Improving On My Current Skill Level | Sharing My Knowledge With Other People