All you need to know about JavaScript Array Methods

All you need to know about JavaScript Array Methods

Array Methods

  1. Length()

  2. Push()

  3. Unshift()

  4. Splice()

  5. Slice()

  6. POP()

  7. Shift()

  8. reverse()

  9. Concat()

  10. Sort()

  11. tosring()

  12. Join()

  13. Fill()

  14. LastIndexOf()

  15. Indexof()

  16. Array includes()

What is Array ?

In Javascript Array is a colllection of elements of any types. Basically in arrays we can store any type of value in it . Values is of type string, integer, boolean and objects also .

Array is represented by the help of [] square brackets and the elements is seperated by a , .

For Example

let array1=['sandeep', 12, true, {} ];

In the above example we make an array and store the array into a variable named array1.

The position of an element in the array is known as its index. In JavaScript, the array index starts with 0, and it increases by one with each element.

For example:

let name=["jitender" , "Amit" , " Raj" ,"Aditya"]

so form above we can say that jitender is at 0th index or 0th position or aditya is at 3rd position.

Interestingly, JavaScript arrays are not of fixed length. You can change the length anytime by assigning a positive numeric value.

How to create an Array ?

Basically their are multiple ways to create an array in javascript.

First One is a straight forward

const array_name = [item1, item2, ...];

Example

const city=["Delhi", "Pune", "Banglore"]

Second one with the help of new keyword

The following example also creates an Array, and assigns values to it

For Example-

const cars = new Array("Saab", "Volvo", "BMW");

How to get elements from the array .

You can access the element from the array by using its index.

const access=array[index];

For Example:

const cars=["Saab", "Volvo", "BMW"]

From the above example if you need to access BMW then you need to put the position of that element inside the square brackets.

const element=cars[2];

Gives the output of -> BMW

Based on your use-cases, you may choose to access array elements one by one or in a loop.

Array Methods

Length()-> If you need to determine the length of the array or how many elements are their in our array. We use length method.

Synatx: array_name.length;

For example:

let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// find the length of the city array
let len = city.length;
console.log(len);

// Output: 4

`

Push -> If you want to add the elements in the array then we can use push method. Push basically adds the element to the end of the array. Returns the new length of the array. This method changes the original array and its length.

Syntax: arr_name.push(element_name);

let city = ["New York", "Madrid", "Kathmandu"];

// add "London" to the array
city.push("London");

console.log(city);

// Output: [ 'New York', 'Madrid', 'Kathmandu', 'London' ]

Unshift -> Like as we discussed above if push basically adds the element to the end of the array.

Unshift adds the elements to the start of the array and returns the new length of the array. This method changes the original array and its length.

syntax : array.unshift(element_name);

let languages = ["Java", "Python", "C"];

// add "JavaScript" at the beginning of the array
languages.unshift("JavaScript");
console.log(languages);

// Output: [ 'JavaScript', 'Java', 'Python', 'C' ]

Splice-> It is basically if we want to add or delete the element inside the array we can do this with the help of this method.

syntax: array.splice(starting_index,delete_count, elementToAdd)

The splice() method takes in:

start - The index from where the array is changed.

deleteCount (optional) - The number of items to remove from start.

elementToAdd (optional) - The elements to add to the start index. If not specified, splice() will only remove elements from the array.

let prime_numbers = [2, 3, 5, 7, 9, 11];

// replace 1 element from index 4 by 13
let removedElement = prime_numbers.splice(4, 1, 13);
console.log(removedElement);
console.log(prime_numbers);

// Output: [ 9 ]
//         [ 2, 3, 5, 7, 13, 11 ]

Slice->The slice() method returns a shallow copy of a portion of an array into a new array object.

Shallow means the value or we can say the element point to the same location .

Returns a new array containing the extracted elements.

Syntax:

arr.slice(start, end)

The slice() method takes in:

start (optional) - Starting index of the selection. If not provided, the selection starts at start 0.

end (optional) - Ending index of the selection (exclusive). If not provided, the selection ends at the index of the last element.

let numbers = [2, 3, 5, 7, 11, 13, 17];

// create another array by slicing numbers from index 3 to 5
let newArray = numbers.slice(3, 6);
console.log(newArray);

// Output: [ 7, 11, 13 ]

Now in this -> In the newArray we have [7, 11, 13] so if we change the element here it will reflect this changes on the numbers array also.

Pop-> The pop() method removes the last element from an array and returns that element. Returns undefined if the array is empty.

Syntax: arr.pop();

let cities = ["Madrid", "New York", "Kathmandu", "Paris"];

// remove the last element
let removedCity = cities.pop();

console.log(cities)         // ["Madrid", "New York", "Kathmandu"]
console.log(removedCity);   // Paris

Shift->As we discussed above pop will delete the element from the last if we want to remove the element form the begining we can use shift.

Syntax->arr.shift()

let languages = ["English", "Java", "Python", "JavaScript"];

// removes the first element of the array
let first = languages.shift();
console.log(first);
console.log(languages);

// Output: English
//         [ 'Java', 'Python', 'JavaScript' ]

After removing the element at the 0th index, it shifts other values to consecutive indexes down

Reverse->The reverse() method returns the array in reverse order.

Syntax: arr.reverse()

let numbers = [1, 2, 3, 4, 5];

// reversing the numbers array
let reversedArray = numbers.reverse();

console.log(reversedArray);

// Output: [ 5, 4, 3, 2, 1 ]

The reverse() method reverses the order of elements in place, it means the method changes the original array.

Concat->The concat() method returns a new array by merging two or more values/arrays.

Syntax: arr.concat(value1, value2, ..., valueN)

let primeNumbers = [2, 3, 5, 7]
let evenNumbers = [2, 4, 6, 8]

// join two arrays 
let joinedArrays = primeNumbers.concat(evenNumbers);
console.log(joinedArrays);

/* Output:
[
  2, 3, 5, 7,
  2, 4, 6, 8 
]
*/

Returns a newly created array after merging all arrays/values passed in the argument.

The concat() method first creates a new array with the elements of the object on which the method is called. It then sequentially adds arguments or the elements of arguments (for arrays).

Sort->The sort() method sorts the items of an array in a specific order (ascending or descending).

Syntax: arr.sort(compareFunction)

let city = ["California", "Barcelona", "Paris", "Kathmandu"];

// sort the city array in ascending order
let sortedArray = city.sort();
console.log(sortedArray);

// Output: [ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]

compareFunction (optional) - It is used to define a custom sort order.

If a User want to sort the array with their specific condition so we can use this compare function.

toString->The toString() method returns a string formed by the elements of the given array.

Syntax-> arr.toString()

// defining an array
let items = ["JavaScript", 1, "a", 3];

// returns a string with elements of the array separated by commas
let itemsString = items.toString();

console.log(itemsString);

// Output: 
// JavaScript,1,a,3

**The toString() method does not change the original array.

Elements like undefined, null, or empty array, have an empty string representation.**

Join-> The join() method returns a new string by concatenating all of the elements in an array, separated by a specified separator.

Syntax-> arr.join(separator)

let message = ["JavaScript", "is", "fun."];

// join all elements of array using space
let joinedMessage = message.join(" ");
console.log(joinedMessage);

// Output: JavaScript is fun.

**The join() method does not change the original array.

Elements like undefined, null, or empty array have an empty string representation.**

Fill->The fill() method returns an array by filling all elements with a specified value.

Syntax-> arr.fill(value, start, end)

// defining an array 
var fruits = ['Apple', 'Banana', 'Grape'];

// filling every element of the array with 'Cherry'
fruits.fill("Cherry");

console.log(fruits);

// Output: 
// [ 'Cherry', 'Cherry', 'Cherry' ]

The fill() method can take 3 parameters:

value - Value to fill the array with.

start (optional) - Start index (default is 0).

end (optional) - End index (default is Array.length), which is always excluded.

If start or end is negative, indexes are counted backwards. Means from the right hand side.

LastIndexof->The lastIndexOf() method returns the index of the last occurrence of a specified element in the array.

Syntax-> arr.lastIndexOf(searchElement, fromIndex)

let priceList = [10, 8, 2, 31, 10, 31, 65];

// finding the index of the last occurence of 31
let lastIndex = priceList.lastIndexOf(31);

console.log(lastIndex); 

// Output: 5

The lastIndexOf() method can take two parameters:

searchElement - The element to locate in the array.

fromIndex (optional) - The index to start searching backwards. By default it is array.length - 1.

Indexof->The indexOf() method returns the first index of occurance of an array element, or -1 if it is not found.

Syntax->arr.indexOf(searchElement, fromIndex)

let languages = ["Java", "JavaScript", "Python", "JavaScript"];

// get the index of the first occurrence of "JavaScript"
let index = languages.indexOf("JavaScript");
console.log(index);

// Output: 1

indexOf() compares searchElement to elements of the Array using strict equality (similar to triple-equals operator or ===).

Syntax-> arr.includes(valueToFind, fromIndex)

Array includes->The includes() method checks if an array contains a specified element or not.

// defining an array
let languages = ["JavaScript", "Java", "C"];

// checking whether the array contains 'Java'
let check = languages.includes("Java");

console.log(check); 

// Output: true

The includes() method can take two parameters:

searchValue- The value to search for.

fromIndex (optional) - The position in the array at which to begin the search. By default, it is 0.

The includes() method returns:

true if searchValue is found anywhere within the array.

false if searchValue is not found anywhere within the array.

** I hope you liked my article if this will be helpful for you please do comment and like.

Thank you **

Did you find this article valuable?

Support jitender singh by becoming a sponsor. Any amount is appreciated!