DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for javaScript's Array Methods.
Hamza Ali
Hamza Ali

Posted on

javaScript's Array Methods.

Array is a data structure whichcontains a set of elements. Each element take up one index of an array. Generally all element of the array are of same type e.g string, integer etc but this is not the case in JavaScript. You can literally add any type of element in an array.
example : [1,2,"Hello",3.5,"world"] this is doable in JavaScript.
After discussing what array is lets move on to the methods of array in JavaScript.

  • PUSH method adds elements to the end of an array and return a new length of an array. It mutates the original array. Example
let arr = [1,2,3]
arr.push("newElement")
//it will push the newElement string to the end of the array.
console.log(arr)
//output
[1,2,3,'newElement']
Enter fullscreen mode Exit fullscreen mode
  • POP as push inserts the new element in the array pop removes the last element of the array. It mutates the original array. Example
let arr = [1,2,3]
arr.pop()
//it will remove the last element of the array which id 3 in this case
console.log(arr)
//output
[1,2]
Enter fullscreen mode Exit fullscreen mode
  • shift removes the first element of the array and return the removed element and also mutates the original array and its length. Example
let arr = [1,2,3]
arr.shift()
//it will remove the first element of the array which in this case is 1
console.log(arr)
//output
[2,3]
Enter fullscreen mode Exit fullscreen mode
  • unshift as shift removes the first element of the array unshift add the new element in the start of the array and return the new length of the array. Example
let arr = [1,2,3]
arr.unshift(4)
//it will add the new element 4 in the start of array and will return the new length of array
console.log(arr)
//output
[4,1,2,3]
Enter fullscreen mode Exit fullscreen mode
  • slice returns selected elements of an array as a new array without mutating the main array. it accepts one or two arguments. slice method also accepts both positive and negative arguments. positive will start from the start of an array and negative will start from the end of an array Example
let arr = [1,2,3,4]
//signal argument
let newArray1 = arr.slice(2)
//it will return the element from the second index to the last index
console.log(newArray1)
//output 
[3,4]
//Two arguments
let newArray2 = arr.slice(1,3)
//it will return element starting from the start argument to the end argument but does not include the end argument.
console.log(newArray2)
//output 
[2,3]

//Negative argument
//singal argument
let newArray3 = arr.slice(-3)
console.log(newArray3)
//output
[2,3,4]

//Two arguments
let newArray4 = arr.slice(-3,-1)
console.log(newArray4)
//output
[2,3]
Enter fullscreen mode Exit fullscreen mode
  • splice add/removes elements in an array at specified place. It mutates the original array.

Example

//Add items to array
const arr = [1,2,3,4]
arr.splice(2,0,5)
//it will add 5 after 3 

console.log(arr)
//output
[1,2,5,3,4]

//remove elements from an array
let arr =[1,2,3,4,5,6]
arr.splice(2,1)
//first argument is the position and the second argument is the number of element you want to remove pass 0 if you don't want to remove any element.

console.log(arr)
//output
[1,2,4,5,6]

//add and remove item at same time

let arr =[1,2,3,4,5,6]
arr.splice(3,1,9,10)
//it will remove one item from third index and add two items there.

console.log(arr)

//output

[1,2,3,9,10,5,6]
Enter fullscreen mode Exit fullscreen mode
  • join return a new string of an array elements either separated by comma or specified separator. Example
let arr = [1,2,3,4,5]
const joinString = arr.join()
//it will return a string of array elements separated by ,
console.log(joinString)
//output
"1,2,3,4,5"

//specifying a separator

const withOperator = arr.join('with')
//output
"1with2with3with4with5" 
Enter fullscreen mode Exit fullscreen mode
  • toString converts an array into string separated by comma. This method is not specific for array only it can be found in every object. Example
let arr = [1,2,3,4,5]
const arrayString = arr.toString()
//output
"1,2,3,4,5"
Enter fullscreen mode Exit fullscreen mode
  • forEach loops through each element of an array and executes the callback function for each element of an array. Example
let arr = [1,2,3,4,5]
var sum = 0
arr.forEach(function(element){
sum = sum + element //element = 1,2,3,4,5
})
console.log(sum)
//output 
15
Enter fullscreen mode Exit fullscreen mode

**Explanation*
For each iteration of forEach element's value will be changed. for first iteration its value will be 1 then for next iteration its value will be 2 and so on and each value will be added to sum.

  • filter returns a new array that filters out the elements of an array. If an element satisfies the condition of callback then it is added to the new array.

**Example*

let arr = [1,2,3,4,5,6]
var filteredArray = arr.filter(function(element){
//it will only add those elements to the new array which are either equal to 3 or greater than 3
return element >= 3
})
console.log(filteredArray)
//output
[3,4,5]
Enter fullscreen mode Exit fullscreen mode
  • includes check if an array contains the element passed to the method. It only returns true or false. Keep in mind includes() is case sensetive. Example
let arr = ['red','blue','yellow','green']
const check = arr.includes('red')
console.log(check)
//output
true

const check2 = arr.includes('white')
console.log(check2)
// output 
false
Enter fullscreen mode Exit fullscreen mode
  • map iterates through each array elements and call the provided callback function for each element of array. It returns a new array and does not alter the main array. Example
let arr = [1,2,3,4,5]
var newArray = arr.map((element)=>
element*2
)
//it will multiply 2 with each element of array and store it in the new array.

console.log(newArray)

//output
[2,4,6,8,10]
Enter fullscreen mode Exit fullscreen mode
  • from creates and array from an object which have length property or is iterate able. Example
const arr = Array.from('12345')
//It will create a new array from the string provided in the from //parameter
console.log(arr)

//output
['1','2','3','4','5']

//from also accepts a map function 

const arrMap = Array.from('12345',(x)=>x*2)
//it will first create an array from the provided string and then //it will run map function on it.

console.log(arrMap)

//output
[2,4,6,8,10]
Enter fullscreen mode Exit fullscreen mode
  • concat Merges two or more array into a new single array. This method does not alters the existing array instead it returns the new array.

Example

let arr1 =[1,2], arr2 = [3,4]

const concatedArray = arr1.concate(arr2)
//this will add both the array in new array. 
console.log(concatedArray)

//output
[1,2,3,4]

//if you want to merge more than two array

const concatedArrayMultiple = arr1.concate(arr2,['hello','world' )
console.log(concatedArrayMultiple)

//output 
[1,2,3,4,'hello,'world']

Enter fullscreen mode Exit fullscreen mode
  • reverse reverses the order of the elements of array, first element becomes the last and last element becomes the first element.it alters the original array. Example
let arr = [1,2,3,4,5]
arr.reverse()
//it will reverse the array 

console.log(arr)

//output 

[5,4,3,2,1]
Enter fullscreen mode Exit fullscreen mode
  • sort It sorts the array according to the provided function if the function is not provided then its sorts the array in ascending of UTF-16. It alters the original array and return the sorted array. Sort is also case sensitive.

Example

let arr = [1,2,5,4,3]

arr.sort()
//this will sort the array in ascending order

console.log(arr)

//output
[1,2,3,4,5]

// to sort the array in descending order we have to provide a function to it

let arr1 = [1,2,4,5,6,3]
arr1.sort(function(a,b){return b-a})
//it will sort the array in descending order

console.log(arr1)

//output

[6,5,4,3,2,1]
Enter fullscreen mode Exit fullscreen mode
  • every tests weather all the elements of an array pass the test implemented by the provided function. If an element fails the test it will return false and will not run the test for the remaining elements. If all the elements pass the test then it will return true. it does not alter the original array.

Example

let arr = [1,2,3,4,5,6]
const value  = arr.every(function(element){
return element <=3
// It will return false because not all the elements are less than or equal to 3 . it will return false after it check 4 because 4 does not passes the test
})

console.log(value)
//output
false

//What if all elements pass the test

const value2 = arr.every(function(element){
return element < 7 
//it will return true because all the elements in the array are less than 7.
})

console.log(value2)

//output
true

Enter fullscreen mode Exit fullscreen mode
  • some tests whether any element of an array pass the test implemented by the provided function. It returns true if an element of an array pass the test and returns false if no element of an array pass the test. If an element passes the test then it will not test the remaining elements.

Example

let arr = [1,2,3,4,5]

const value = arr.some(function(element){
return element > 7
//it will return false because no element in the given array is greater than 7
})

console.log(value)

//output 
false

//What if an element passes the test

const value1 = arr.some(function(element){
return element === 3 
// it will return true because 3 is present in the array and after finding 3it will not test the remaining elements
})

console.log(value1)
//output
true
Enter fullscreen mode Exit fullscreen mode
  • reduce executes user provided reducer callback function for each element of an array. It passes the return value of previous elements callback function to the next elements callback function and in the end it returns a single value. The easiest way to understand this is to get the sum of an array's element using reducer.

Example

let arr = [1,2,3,4,5,6]

const sum = arr.reduce(function(prevValue,currentValue){
return prevValue + currentValue
})

console.log(sum)
//output
21
Enter fullscreen mode Exit fullscreen mode
  • findIndex it returns the index of the first element of an array that satisfies the provided callback function.

Example

let arr = [1,2,3,4,5]
const index = arr.findIndex(function(element){
return element = 3
//it will return the `index` of 3 if it finds it in the array otherwise it will return `-1`
})

console.log(index)
//output
2
Enter fullscreen mode Exit fullscreen mode

Conclusion
Did you guys find the methods that I have listed above useful. If you have any suggestion leave them in the comments.

That's all from me! Bye!

Top comments (3)

Collapse
 
dannyengelman profile image
Danny Engelman
Collapse
 
umermahmood11 profile image
UmerMahmood11

Thanks. The content was very helpful and well explained.

Collapse
 
hat52 profile image
Hamza Ali Author

Thank you ๐Ÿ˜Š

๐Ÿคฏ

"I made 10x faster JSON.stringify() functions, even type safe"

โ˜๏ธ Must read for JS devs