Arrays In Javascript

Arrays In Javascript

Guide On Array In JavaScript And Its Methods

What Is Array

An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.

Example of Array:

const ArrayName = [100, true, 'WelcomUser', {}];

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.

So, for example, in the above array, the element 100 is at index 0, true is at index 1, 'WelcomeUser' is at index 2, and so on.

The number of elements in the array determines its length. For example, the length of the above array is four.

Interestingly, JavaScript arrays are not of fixed length. You can change the length anytime by assigning a positive numeric value. We will learn more about that in a while.

How To Create an Array In Javascript

You can create an array in multiple ways in JavaScript. The most straightforward way is by assigning an array value to a variable.

const nameArray = ['Virat', 'Sachin', 'MSD'];

You can also use the Array constructor to create an array.

const nameArray = new Array('Virat', 'Sachin', 'MSD');

How To Add & Remove Elements In an Array

Use the push() method to insert an element into an array. The push() method adds an element at the end of the array. How about we add some peanuts to the salad, like this:

const nameArray = ['Virat', 'Sachin', 'MSD'];
nameArray.push('Ashwin');

Now the nameArray is:

['Virat', 'Sachin', 'MSD', 'Ashwin' ]

Note that the push() method adds an element to the end of the array. If you want to add an element to the beginning of the array, you'll need to use the unshift() method.

const nameArray = ['Virat', 'Sachin', 'MSD','Ashwin'];
nameArray.unshift('Siraj');

Now the nameArray is:

['Virat', 'Sachin', 'MSD', 'Ashwin', 'Siraj' ]

The easiest way to remove a single element from an array is using the pop() method. Every time you call the pop() method, it removes an element from the end of the array. Then it returns the removed element and changes the original array.

const nameArray = ['Virat', 'Sachin', 'MSD','Ashwin','Siraj'];
nameArray.pop();
console.log(nameArray) // ['Virat', 'Sachin', 'MSD','Ashwin']

Use the shift() method to remove an element from the beginning of an array. Like the pop() method, shift() returns the removed element and changes the original array.

const nameArray = ['Virat', 'Sachin', 'MSD','Ashwin'];
nameArray.shift();
console.log(nameArray) // ['Virat', 'Sachin', 'MSD']

How to Get Elements from an Array in JS

You can access and retrieve elements from an array using its index. You need to use the square bracket syntax to access array elements.

const element = array[index];

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

When you're accessing elements using an index like this:

const nameArray = ['Virat', 'Sachin', 'MSD'];
nameArray[0];
nameArray[1];
nameArray[2];

You can also loop through the array using a regular for or forEach loop, or any other loop.

const nameArray = ['Virat', 'Sachin', 'MSD'];

for(let i=0; i<nameArray.length; i++) {
  console.log(`Element at index ${i} is ${nameArray[i]}`);
}

JavaScript Array Methods

  • slice: This method is used to extract a specific portion of an array. It returns a new array and does not change the original array. Here start & end denotes the index of elements of the array. Syntax:

      slice() 
      slice(start)
      slice(start, end)  // end is not included
    

Example:

const indianSquad= [ 'Virat', 'Sachin', 'MS', 'Ashwin', 'Rahul'];
console.log(indianSquad.slice(2));   // ['Virat', 'Sachin', 'MS',]
console.log(indianSquad.slice(2, 4)); // [MS', 'Ashwin', 'Rahul']
console.log(indianSquad.slice(1, 4));  // ['Sachin', 'MS', 'Ashwin', 'Rahul']
console.log(indianSquad.slice(-2)); // ['Ashwin', 'Rahul']
  • concat():

This method is used to merge two or more arrays. This method does not change the original arrays but returns the new merged array.

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul'];
const indiaBolwer= ['Kapil', 'Anil', 'J Shrinath', 'Zaheer', 'Bhuvneshwar'];
const indiaSquad = indiaBatter.concat(indiaBolwer);
console.log(indiaSquad);
// [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Kapil', 'Anil', 'J Shrinath', 'Zaheer', 'Bhuvneshwar']
  • fill():

This method fills all the array (or only the specified) elements with a static value. This method modifies the original array.

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul'];
indiaBatter.fill('Yuvraj');
console.log(indiaBatter);
// [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj']
  • includes(): This method is used to check whether an element is present in an array or not. If the element is present then it will return true else it returns false.

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj'];
indiaBatter.includes('Shikhar'); // false
indiaBatter.includes('Virat'); // true
  • indexOf(): This method is used to find the index of an element in an array. If an element is not present then the indexOf() method returns -1

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj'];
indiaBatter.indexOf('Virat'); // 0

If an element is present more than one time then the indexOf() method returns the index of its first occurrence. If we want to know the last occurrence of that element then use lastIndexOf()

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj'];
indiaBatter.indexOf('Shikhar'); // -1
  • reverse():

This method reverses the position of all the elements in an array. This method modifies the original array.

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj'];
indiaBatter.reverse(); // ['Yuvraj', 'Rahul', 'Laxman', 'MS','Sachin','Virat']
  • sort():

This method first converts all the elements of the array into a string and then sorts them in ascending order. This method modifies the original array.

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj'];
indiaBatter.sort(); // ['Laxman','MS', 'Rahul', 'Sachin', 'Virat', 'Yuvraj']
  • at(): As we have seen above, to access the elements of an array backward we use the length of an array. at() method allows us to directly traverse the array backward without using the length method by directly using a negative value.

Example:

const indiaBatter= [ 'Virat', 'Sachin', 'MS', 'Laxman', 'Rahul', 'Yuvraj'];
indiaBatter.at(2); // MS
  • filter():

The filter() method creates a new array with all the elements that satisfy the condition mentioned in the function. Let's find an age which is greater than 18.

Example:

const ages = [32, 33, 16, 40];

document.getElementById("demo").innerHTML = ages.filter(checkAdult);

function checkAdult(age) {
  return age >= 18;  // 32,33,40
}
  • reduce()

    The reduce() method applies a reducer function on each of the array elements and returns an output value.

Example:

const numbers = [190, 80, 45];
document.getElementById("demo").innerHTML = numbers.reduce(myFunc);

function myFunc(total, num) {
  return total - num; // 55 (Subtracting the numbers in the array, starting from the left:)
}

Takeaway

I hope you've found this article insightful, and that it helps you understand JavaScript arrays more clearly.

That's it for the day see you in the next blog until then...

Keep Writing Code ❤️