Array methods Every JS developer must know.

A dive into array methods

Array methods Every JS developer must know.

Intro

An array is a widely used data structure in the JavaScript language.

An array is a list-like data structure consisting of a collection of elements. Each element is determined by its index. The count of the index start's from 0 and the last index decides the length of an array.

While learning I encountered a lot of places where the array was implemented and JavaScript array methods made a lot of things easier. Array provides plenty of methods. So I decided to write a blog about it. Documenting what I Have learned.

All this content is freely available to read on the internet. I referred to the MDN Web docs for understanding.

Functions

push() -

The push() method is used to add one or more elements to the end of the array. This method changes the length of an array.

  • parameters :

    the element(s) that are added to the end of an array.

  • return :

    the new length of an array.

pop() -

The pop() method removes only the last element in an array.

  • return :

    the removed element.
>let tech=['html','css']

>tech.push('JS')
<(3) //returns new length ['html','css','JS']
>tech.push('react','angular') //adding more than one element
<(5) //['html', 'css', 'JS', 'react', 'angular']

>let tech=['html', 'css', 'JS', 'react', 'angular']
>tech.pop()
< 'angular' // return the removed element

shift() -

The shift() method removes the first element from an array. This method changes the length of an array. It removes the 0th element and shifts the indexes of all consecutive elements down.

  • return :

    the removed element

unshift() -

The unshift() method add one or more elements to the start of an array. If more than one element is added then it is added as a chunk to the start.

  • parameters :

    the elements to add at the front of an array.

  • return :

    new length of array

>let arr1=[3,4,5,6]
>arr1.shift()
< 3 //returns 1
//arr1=[4,5,6]

>arr1.unshift(3)
< 4 //returns the new length
//arr1 = [3, 4, 5, 6]

>arr1.unshift(1,2) //adding more than 1 elements
< 6 //returns the new length
//arr1=[1, 2, 3, 4, 5, 6]

reverse() -

The reverse() as the name suggest's reverses an array. The original array is changed.

  • return :

    reversed array
let arr=[1,2,3,4,5]
let revArr=arr.reverse()
//revArr = [5,4,3,2,1]

join() -

The join() method creates and returns a string concatenating all the elements of an array it is called upon.

  • parameters [optional] :

    separator that concatenates all array element, if nothing is passed the array elements are separated with a comma (",")

  • return :

    The string with all array elements joined

let letters=['s','u','s','h','a','n','t']
let joinedLetters=array.join()
//joinedLetters = 's,u,s,h,a,n,t' //returns string joined with (",")
let joinedLetters2=array.join("-")
//joinedLetters2 = 's-u-s-h-a-n-t' //returns string joined with separator ("-")

slice() -

The slice method creates a shallow copy of part of the array into a new array-like object from start and end values passed as parameters. The original array is unchanged.

  • parameters :

    takes two parameters and both are optional. The first is a start, it's the starting index from where to start extraction. Another is end the index where to end the extraction. The element at end index is not included in the new array. The negative index can also be passed here. If the end is not present then the extraction goes on till the last index.

  • return :

    new array object containing the extracted elements.

let itemInBag= ["apple","oranges","banana","cherry","cabbage","spinach","milk","butter"]
let fruits=itemInBag.slice(0,4) //starts extraction from 0th index and ends at 4th(done not include end index)
//fruits = ['apple', 'oranges', 'banana', 'cherry']

let dairy=itemInBag.slice(-2) //extracts the last to index
//dairy = ['milk', 'butter']

let veggies=itemInBag.slice(-4,-2) //extract last 4th to last 2nd(doesn't include 2nd) index
//veggies=['cabbage', 'spinach']

Higher-Order Functions

While learning JavaScript we may have come across the term "higher-order functions".These functions are used heavily in JavaScript, which makes it suitable for functional programming. It may sound like a really complex thing to understand, but it isn't.

Higher-Order Functions are functions that operate on other functions, either by taking them as arguments or returning them.

Let's discuss some of the most used functions:

map() -

The map() method transforms an array by applying a function to its elements and building a new array from its returned values. The map function will take returned values from callback functions and create a new array. The new array created has the same length. The original array remains unchanged.

  • parameters (callback function) :

currentValue : The current element being processed.

currentIndex[optional] : The index of the current element.

array [optional] : The array map is used upon.

  • return :

    a new array with each array being the result of a callback function.
let arr=[1,2,3,4,5]
let doubleArr=arr.map(elem => elem*2 ) //callback function to get double of each element
//arr = [2, 4, 6, 8, 10]

filter() -

The filter() method finds all the elements that satisfy the condition or of same type and build a new array out of it. Each element is tested by a callback function. Rather than deleting the elements from original array based on return value from callback function it builds a new array.

  • parameters (callback function) :

currentValue : The current element being processed.

currentIndex[optional] : The index of current element being processed.

array [optional] : The array filter() is called upon.

  • return -

    A new array that passes the test(callback function). An empty array is returned if no element pass the test.
let students = [{id:1,dept:"CS",name:"Sachin"} , {id:2,dept:"MECH",name:"Ram"},{id:3,dept:"CS",name:"Virat"},{id:4,dept:"ENTC",name:"Sushant"}]
let filteredDept=students.filter(student=> student.dept=="CS") //filtering based on dept="CS"
//filteredDept = [{id: 1, dept: 'CS', name: 'Sachin'},{id: 3, dept: 'CS', name: 'Virat'}]

let filterName=students.filter(student => student.name.length>6) //filter whose name length>6
//filterName = [{id: 4, dept: 'ENTC', name: 'Sushant'}]

reduce() -

The reduce() method applies reducer across all element of array and returns a single value. It returns a single value calculated on each element of array. The reducer is initialized and processed throughout the array, at each step calculates the result and adds to previous steps result till last index of array.

  • parameters :

callback function:

  • prevoiusValue - The resulting value from last callback function i.e. Accumulator
  • currentValue - The value of current element.
  • currentIndex - The index of current element.
  • array [optional] - The array reduce() is applied upon.

initialValue [optional] -

  • If it is provided, then previousValue will be equal to initialValue and currentValue equal to first element.
  • If it is not provided, then previousValue is set to first first element and currentValue is the second element of array.

  • return :

    The value returned after running reducer function on all array elements.

let report={ id:1,
             marks:[25,32,44,38,29,41],
           }
let totalMarks=report.marks.reduce((previousValue,currentValue) => previousValue+currentValue,0)
//returns total of all elements of array, initialValue is set to 0
report['total']=totalMarks
//report={ id:1,marks:[25,32,44,38,29,41],total:209}

Conclusion

Before we end, I hope you got an insight into the array method that makes our programming easy. To get a better grip over the concept we need to solve some problems and practice them.

Other than this concat(),sort(),find(),findIndex(),fill(),forEach(),some(),every() ... are some very useful array method.

Let's connect. You will find me active on Twitter(@MasterThinking). Please feel free to give a follow.