Array Methods
To work with data effectively in JavaScript it is of paramount importance that one is comfortable with the methods via which you can manipulate data in an array. This is because most data that is handled in JavaScript usually comes either in form of an object or an Array. Today we will be talking about arrays.
The Ends' Manipulation
We have with us; provided by JavaScript; features to add or remove elements from the ends of the array. So let's start with the push() and pop() methods.
For this segment the array we will be working with will be:
const arr = [1,2,3,4,5];
push()
The method allows us to push a new element at the end of the array
arr.push(6);
This will add 6 to the end of the array making it as:
// arr = [1,2,3,4,5,6];
The common thing that people often miss is that this function actually has a return value. And the return value is the length of the new array. In the above case when we did the push if we saved it to a variable it would have printed 6 (not the last element but the length of the array).
pop()
This method is used to remove the last element of the array. For example:
const el = arr.pop();
The last element (in our case 6) is removed. And that removed element is returned.
The array changes to:
// arr = [1,2,3,4,5 ]
We also have two methods that remove or add from the start of the array.
shift()
This method removes the first element from the array and returns that element.
const rmel = arr.shift();
Array changes to:
// arr = [2,3,4,5]
And the value of rmel = 1.
unshift()
This function is the opposite of shift and adds an element as the first element of the array and returns the new length of the array after the addition. For example:
const newlen = arr.unshift(1);
Here we get back the returned value as 5 as the new array becomes:
// arr = [1,2,3,4,5];
Working on Every Element as a Group
Now that we can add and remove elements from the end of the array - we should look into some array functionalities that allow us to perform operations on all elements of the array. For example - creating a new array from the elements of the old one , filtering out some elements based on a criteria, checking if all or some of them satisfy a given condition finding out a unique element in the array based on a defined requirement.
array.map()
The map method in an array takes a callback function as an argument and for every element of the array runs that callback function. When it gets a response from it - it takes that value and append it to a new array that is same for one call of map() method. When the process has been done for all elements that new array is returned.
const myarr = [1,2,3,4,5];
const sqaureArray = myarr.map( (el)=>el*el );
Here we can say that we have passed a callback that will take an element and return its square. The map() function will call it for every element and append the result to a array it defines itself. At the end it will be returned.
squareArray = [1,4,9,16,25];
array.filter()
This method is used to get a new array where each element is:
from the previous array.
Has been verified on a certain criteria.
If both the conditions are satisfied we will get that element in a filtered array. The callback passed to this method must return a true or false value
For example:
const filtered = squareArray.filter( (el)=> el>10 );
The callback passed will check each element for if its greater than 10. If yes it will be included or else it will be rejected. Here the array we will get back will be:
filtered = [16,25];
Why to use these?
Now imagine if you had to write entire traditional for loops for maps or filters. Like for map it would have been like:
const myarr = [1,2,3,4,5];
const sqaureArray;
for(let i =0; i<myarr.length ; i++)
{
sqaureArray.push( myarr[i]* myarr[i]);
}
Now compare that to previous code:
const myarr = [1,2,3,4,5];
const sqaureArray = myarr.map( (el)=>el*el );
Amount of code written is drastically reduced along with better readability. And same for filter.
const filtered = [];
for(let i=0; i< sqaureArray.length ; i++)
{
let el = squareArray[i];
if(el*el>10)
{
filtered.push(el*el);
}
}
Again such a verbose code against mere a one-liner:
const filtered = squareArray.filter( (el)=> el>10 );
Which one would you prefer?
array.forEach()
In the above methods we are getting back a new array by performing some operation on each element. But what if we just want to perform an operation on each element and not want a new array back.
Here we can use forEach:
let squareSum = 0;
const arr = [1,2,3,4,5];
arr.forEach( (el)=>{
squareSum += el*el;
} );
Here we are getting each element to be squared and added to the squareSum. We don't get any new array back here but perform an operation. We can also optionally pass an index as an argument to the callback to get access to the index we are on. This argument is automatically filled by the forEach method. For example:
const squareSum = 0;
const arr = [1,2,3,4,5];
arr.forEach( (el,index)=>{
console.log('Index number :' , index);
squareSum + = el*el;
} );
Here we can see that we have the access to the index.
array.reduce()
The reduce method in JavaScript allows us to go though all values and returns a single value by getting the result into a variable calculated on the basis of a function passed an argument.
The most basic concept is:
array.reduce(callbackFunction , initialValue);
If no intialValue is specified reduce will consider the first value of the array as the initial value. If the array is empty a type error will be thrown.
Now for the callback function we will have 2 arguments :
Accumulator
This is the place where the final value will be stored and returned and this is also the value which is usually modified on runtime to get the answer.CurrentValue
This is the variable that represents an array element . In general we use this variable in our callback to define the value of the array for a every iteration and how we will use it.
Now in our function we modify the Accumulator with the currentValue. When all operations are done the Accumulator value is returned.
For example:
const arr = [1,2,3,4,5];
const sumofSquares = arr.reduce(
//argument 1 of reduce
(answer,element)=> answer+= element*element,
//argument 2 of reduce
0 //The initial Value
);
The final answer will be in sumofSquares as 55.
The reduce function sometimes feels a little complex but with time, its use cases and syntax will become more known to the programmer.
There are many functions for arrays and not all can be covered here. But using these functions will surely make life easier while working with JavaScript while also helping us to understand other code bases better. One must go out and explore more methods for themselves as this will help them improve. Lets put no cap to our information level and keep on learning and growing.