DEV Community

Susan Wangari
Susan Wangari

Posted on

JavaScript Array Methods

For those of us new in programming, arrays may not be so familiar.No worries, we shall dive right into it.

So what is an array?
An array is a collection of one or more elements of either the same type or different types.The length of an array is not limited.It lets you store multiple elements in a single variable.The elements can be strings, numbers or boolean.
Example
let myArray = ["A", "B", "C", 12, true];
//shows an array with 3 strings, 1 number and a boolean value

Array Methods

Every method in an array causes an impact; it changes the array in one way or another.We will look at 3 array methods.These are: map, filter and reduce.

1.map() or Array.prototype.map() creates a new array with the results of calling a function for every array element.It does not change the original array.
Example
let myNumbers = [20, 21, 22];
let myArray = myNumbers.map(multiply = (num) => num * 2);
console.log(myArray);

//myArray returns 40, 42,44

2.filter() or Array.prototype.filter() creates a new array containing only the elements for which the filtered function returns true.It also does not mutate or change the original array.
Example
const names = ["Susan", "Jane", "John", "Tom"];
const newNames = names.filter(names => names.length < 5);
console.log(newNames);

//newNames returns ["Jane", "John" and "Tom"]

3.reduce() or Array.prototype.reduce() as the word suggests, it reduces an array to a single value.This is achieved using a callback function that is called on each iteration.
A *callback function is a function that is passed as a parameter to another function.*It is run inside of the function it was passed into.A callback function accepts 4 arguments.The 1st argument is the accumulator which gets assigned the return value of the callback function from the last iteration.The 2nd argument is the current value which is the current element being processed in an array.The 3rd argument is the index of the current element and the fourth argument is the array upon which reduce() is called upon.The 3rd and 4th arguments are optional.
A perfect example of where reduce can be used is in adding the elements of an array.
const ourArray = [5, 6, 8];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(ourArray.reduce(reducer));

//this code returns 19

Its a wrap.I hope we have all learnt how to apply array methods map, filter and reduce.

Top comments (0)