Photo by Pierre Bamin on Unsplash
JavaScript Array methods and when to use them
A brief introduction to common array methods with some examples
JavaScript Arrays
Arrays in javascript are dynamically sized which means one can increase or decrease the number of elements it can hold on the go, also they can contain different types of values it can be a mixture of different data types.
A quick note about the length and last element index (taken from MDN ) to not get confused,
- JavaScript arrays are zero-indexed: the first element of an array is at the index
0
, the second is at the index1
, and so on — and the last element is at the value of the array'slength
property minus1
.
Example:
let dynamicProperty = ["a","b","c",4,5,6,"hello"]
//Before
console.log(dynamicProperty) // ["a","b","c",4,5,6,"hello"]
dynamicProperty.push("world")
//After
console.log(dynamicProperty) //["a","b","c",4,5,6,"hello","world"]
Methods :
JavaScript provides a wide range of methods (functions) for manipulating Arrays. I'll be explaining a few common ones, feel free to comment for adding some other methods as well.
- array.length
To know the length of an array we use .length
method which returns a number that is the length of that array
Example:
const numbers=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]
console.log(numbers.length) //100
- array.push(element)
For adding some data at the end of an array push method is used. It's like I want to add a "Bread" to my grocery list array.
It will update the list with the new element at the end of it.
Example:
let groceryList = ["Milk","Cheese", "Butter"]
groceryList.push("Bread")
console.log(groceryList); //["Milk","Cheese","Butter","Bread"]
- array.unshift()
Similar to push, unshift method add element from the start and returns the updated length of the array.
One can pass n numbers of element to the unshift method it will add all the elements to the array from the start.
Example:
let stack = ["Out"];
console.log(stack.unshift("First", "In", "First")) // 4
console.log(stack) //["First","In","First","Out"]
-array.pop()
For removing an element from the end of an array and returning it.
Example:
let imposterAmongUs = ["Red","Blue","Green","Pumpkin"];
console.log(imposterAmongUs.pop()) //"Pumpkin"
- array.shift()
Just like pop, shift removes an element from the start of an array and returns it.
Example:
let imposterAmongUs = ["Apple","Potato","Onion","Peas"]
console.log(imposterAmongUs.shift()); //Apple
- array.slice()
The literal meaning of a slice is a portion of a thing, similarly for getting some portion of an array we use the slice method.
For getting a portion of an array (won't change the original array) we need to have a starting index and an ending index, that we pass in the slice method like array.slice(start, end).
By default, the values of start and end if not passed are 0 and the length of the array. Like array.slice(0, array.length)
is the same as array.slice()
.
We pass the index we want to start from and pass on the end index + 1 we want to go to as the end is excluded.
A small note slice does not change the original array.
Example:
const numbers = [0,1,2,3,4,5,6,7,8,9];
console.log(numbers.slice()) //[0,1,2,3,4,5,6,7,8,9]
console.log(numbers.slice(3)) //[3,4,5,6,7,8,9]
console.log(numbers.slice(3,7)) //[3,4,5,6]
//quick quiz what will be the output of below line.
console.log(numbers.slice(9,100))
//You can answer in the comment
-array.splice()
For updating an array we use the splice method.
We update it by passing the starting index from where we will start inserting the other elements and we also pass a second parameter to remove n numbers of elements to remove from starting and after that, all the parameters passed are added to the array.
Breaking it into three parts:
1 - Pass the starting index from where we need to start updating values
2 - Passing the number of elements I want to remove after passing starting index
3 - Pass other elements that are going to be added to the array
Example:
let alphaNumericArray = ["a","b","c",1,2,3];
alphaNumericArray.splice(3,0,"e","f","g") //read as starting from index 3 remove 0 elements and add the passed elements
console.log(alphaNumericArray) // ["a","b","c","e","f","g",1,2,3]
alphaNumericArray.splice(0,3,4,5,6);
console.log(alphaNumericArray) // alphaNumericArray.splice(0,3,4,5,6);
- array.concat()
For adding two or more than two arrays we use concat method.
This method does not change the original array but returns the new array that is concatenated.
Example:
let alphabets = ["a","b","c","d","e"];
let numerics = [1,2,3,4,5,6,7]
const alphanumeric = alphabets.concat(numerics)
console.log(alphanumeric); //["a","b","c","d","e",1,2,3,4,5,6,7]
- array.include()
For checking if an element is present in that array, it checks for the first occurrence of the element and returns true.
We can also control from which index we should start searching.
Example:
let array = ["a","b","c","d","e","f"]
console.log(array.includes("c")) //true
console.log(array.includes("c",3)) //false
console.log(array.includes("f",100)) // Guess the output
- array.indexOf()
It returns the indexOf first occurrence of an element if it's present in the array and if not it returns -1, it starts searching from the 0th index.
Example:
let findAndLocateMe = ["i","me","hello", "me"];
console.log(findAndLocateMe.indexOf("me")); //1
console.log(findAndLocateMe.indexOf("find")); //-1
- array.lastIndexOf()
Just like indexOf returns the first occurrence of an element from start, lastIndexOf starts searching from the end and returns the index of the first occurrence of an element passed.
Example:
let findAndLocateMe = ["i","me","hello", "me"];
console.log(findAndLocateMe.lastIndexOf("me")); //3
console.log(findAndLocateMe.lastIndexOf("find")); //-1
- array.join()
Joining elements of an array by a common element we use array.join(). A use case can be converting an array to comma separated string.
Example:
let introduction = ['Welcome','To','My','Blog'];
console.log(introduction.join('')); //WelcomeToMyBlog
console.log(introduction.join(' ')); //Welcome To My Blog
console.log(introduction.join(123)); //Welcome123To123My123Blog
So that's all for the read from my side, you can comment out more useful methods in the comment if you would like to add on.
Happy Learning!!