Top 10 array methods in JS with practical implementation

Top 10 array methods in JS with practical implementation

Hey JavaScript developers! Hope you're enjoying your programming journey.

If you've been coding for a while, you’re probably familiar with arrays. They are one of the most fundamental data structures in any programming language. But did you know that mastering array methods can be a game-changer. However, if you struggle to understand or use them properly, they might become a hurdle in your development journey.

In this article, we’ll dive deep into JavaScript array methods—not just understanding them, but also implementing them in real-life scenarios.

So, fasten your seatbelt, and let’s explore the world of JavaScript arrays! 🚀

Array:

Array is a collection of data. In JavaScript array is considered as a “non-primitive” data. IN JS an array can store different data-types.

There are 2 ways to declare an element. Here the syntaxes:

Using Array Literals:

let team = ["Player1", "Player2", "Player3", "Player4"];
console.log(team) // outputL:  [ 'Player1', 'Player2', 'Player3', 'Player4' ]

Using Array Constructor:

let team = new Array("Player1", "Player2", "Player3", "Player4");
console.log(team) // outputL:  [ 'Player1', 'Player2', 'Player3', 'Player4' ]

Top 10 Array methods:

In this array we will be using array and array methods to create a cricket team. We’ll be recruiting players, removing them and may more.

Rohit Sharma (c), Shubman Gill, Virat Kohli, Shreyas Iyer, KL Rahul, Ravindra Jadeja, Shardul Thakur, Jasprit Bumrah, Mohammed Siraj, Kuldeep Yadav, Mohammed Shami, Ravichandran Ashwin, Ishan Kishan, Prasidh Krishna, Suryakumar Yadav.

Initiate a team:

So the BCCI board decided Rohit Sharma to be the captain of the Indian team and the team is named “Indian_main_team”. So here’s how we can initiate the team by including the captain.

let Indian_main_team = ["Rohit Sharma"];
console.log(Indian_main_team);  //output: [ 'Rohit Sharma' ]

Add more players:

After consulting with the team captain Rohit Sharma BCCI board decided to include Virat Kohli as the Vice captain.

1. Array.push():

Indian_main_team.push("Virat Kohli");
console.log(Indian_main_team);  //output: [ 'Rohit Sharma', 'Virat' ]

After that The board consulted among themselves and two captains and selected 9 players to add in the main team.

Here’s is the pictorial representation of Array.push() method:

Adding multiple items in array:

Indian_main_team.push( **"Shubman Gill", "Shreyas Iyer", "KL Rahul", "Ravindra Jadeja", "Shardul Thakur", "Jasprit Bumrah", "Mohammed Siraj", "Kuldeep Yadav", "Mohammed Shami"**);
console.log(Indian_main_team);  //output: [ 'Rohit Sharma', 'Virat' ]
//output:
/*[
  'Rohit Sharma',
  'Virat',
  'Shubman Gill',
  'Shreyas Iyer',
  'KL Rahul',
  'Ravindra Jadeja',
  'Shardul Thakur',
  'Jasprit Bumrah',
  'Mohammed Siraj',
  'Kuldeep Yadav',
  'Mohammed Shami'
]*/

BCCI board also created a 4 men squad as extra players. so that if a player from the main team gets injured they can be replaced.

let extra_players = ["**Ravichandran Ashwin", "Ishan Kishan", "Prasidh Krishna", "Suryakumar Yadav"**];
console.log(extra_players)
// output:
/*
[
  'Ravichandran Ashwin',
  'Ishan Kishan',
  'Prasidh Krishna',
  'Suryakumar Yadav'
]
*/

Array.push() method is used to add one or more elements in an array. It changes the original array.

Practicing the entire team together (Joining 2 arrays):

When team India practice the main team and the extra players practice together. So while practicing the group consists of 15 players and here’s how they’re gathered together:

2. Array.concat():

.concat() can join 2 arrays together:

console.log(Indian_main_team.concat(extra_players));

// output:
/*
[
  'Rohit Sharma',
  'Virat',
  'Shubman Gill',
  'Shreyas Iyer',
  'KL Rahul',
  'Ravindra Jadeja',
  'Shardul Thakur',
  'Jasprit Bumrah',
  'Mohammed Siraj',
  'Kuldeep Yadav',
  'Mohammed Shami',
  'Ravichandran Ashwin',
  'Ishan Kishan',
  'Prasidh Krishna',
  'Suryakumar Yadav'
]
*/

Spread Operator (...):

The same operation can be performed by Spread Operator:

let total_team = [...Indian_main_team, ...extra_players];

The reason why spread operator is more useful than .concat() is because with the help of Spread Operator you can add as many arrays as you want.

Here’s an example:

let new_array = [...array1, ...array2, ...array3, ...arra4, ...array5];

Remove the captain:

Due to some issues Rohit Sharma is removed from the team temporarily. This is how the first player is removed from the team:

3 .shift()

total_team.shift();
console.log(total_team);
// output: Everyone except  Rohit Sharma

.shift() Removes the first element of an array.

Board Meeting with Captains (Slicing an array):

4 .slice()

Before the match the BCCI board wanted to conduct a meeting with the captains only. So they summoned Rohit Sharma and Virat Kohli from the team. And this is how they git summoned:

let captains = total_team.slice(0, 2);
console.log(captains)
//outPut: [ 'Rohit Sharma', 'Virat' ]

This is how .slice() works:

let array = [a1, a2, a3, a4, a5, a6, a7, a8]
array.slice(start_index, end_index);

Here

  • the slice() method slices a portion of array and displays without changing the original array.

  • The slicing starts from the start_index input given by the user

  • The slicing ends just an index before the end_index. And the end_index gets ignored by .slice() method. (Just like you get ignored by your crush 😜).

Here’s a pictorial explanation:

Virat and Kohli under leadership training:

After a some discussion, BCCI board decided to sent Virat and Rohit to go under some leadership training for a week so that they can lead the team better. Till that time India will have 13 players to practice.

This is how the team will be managed:

5 .splice():

let captains_under_training = total_team.splice(0, 2);
console.log(captains_under_training);  // output: ['Rohit Sharma', 'Virat' ]
console.log(total_team); // the original team git got changed
//output:
/*[
  'Shubman Gill',
  'Shreyas Iyer',
  .
  .       rest of the players
  .
  'Suryakumar Yadav'
] */

.splice() works different than .slice() except:

This is how .splice() :

arr.splice(index, deleteCount, elementToAdd)

You might think why not shift() ? It also removes element. The reason is .shift() only removes 1st element without control. But you can control .splice() .

This is how the .splice() works.

  • index: Position to insert

  • deleteCount: Number of elements to remove (0 to insert without deleting)

  • elementToAdd: The element to insert.

features of .splice()

  1. .splice() changes the original array.

  2. .splice() can add or remove elements from array.

.splice() is used mainly to remove or add items at specific range. Here’s how.

Shreyas Iyer and KL Rahul removed for personal reason:

Shreyas Iyer git some personal problems and git removed from the team due to some personal issues:

total_team.splice(3, 2);
console.log(total_team); //output: Total team except Shreyas Iyer and KL rahul

Here, total_team.splice(3, 2);

3 is the starting string and 2 is how many elements do I want to remove. If I gave 4 instead of 4, then 4 elements(or players here) would have removed.

Pictorial representation of how Array.splice() works for removing items:

Shreyas Iyer and KL Rahul came back to the team:

After their personal problems were solved, they finally came back to the team:

total_team.splice(3, 0, "Shreyas Iyer", "KL Rahul");
console.log(total_team); //output: Shreyas Iyer", "KL Rahul are back

Pictorial representation of how Array.splice() works for adding items:

Virat and Kohli return from leadership training:

After the completion of the leadership training it’s time for Virat and Kohli to return to the team. How will they go back to their places? This is how:

We have used splice() to remove or add element but there is one method that can add element specially to the beginning of the array.

6 .unshift():

total_team.unshift("Rohit", "virat");
console.log(total_team); // The original array is changed

// output:
/*
[
  'Rohit',
  'virat',
  'Shubman Gill',
  .
  .     rest of the players
  .
  'Suryakumar Yadav'
]
*/

.unshift() is used to add elements at the top or beginning of an array. Although unshift is considered as a bad practice as it is quite expensive operation on the memory. But in small cases like these it can be used.

Remove the last extra player because of injury:

7 .pop()

total_team.pop()
console.log(total_team);  // 'Suryakumar Yadav' got removed

// output:

/*
[
  'Rohit',
  'virat',
  .
  .
  .
  'Prasidh Krishna'
]
*/

.pop() is used to remove the last element of the array.

Here is the pictorial description:

Sort the players’ name alphabetically:

One day BCCI sent an email that for some official reasons they need all the players’ names with their signature beside it, alphabetically.

Here’s how it is done:

8 .sort()

total_team.sort();
console.log(total_team); 
// output:
/*
[
  'Ishan Kishan',
  'Jasprit Bumrah',
  'KL Rahul',
  .
  .
  .
  'Virat'
]
*/

.sort() method sorts all the elements alphabetically

Position of Shubman Gill:

Before the match starts the board member want to know when each player was coming to field for batting.

And this is how they get to know the batting number of Shubman Gill:

9 .indexOf():

console.log(total_team);
console.log(total_team.indexOf("Shubman Gill")); // output: 2

Array.indexOf() takes an element of an array as an input and returns the index of it.

NOTE: Remember the index of an array starts from 0 that’s why index of “ Shubman Gill” whose position is 3 (before sorting) came out to be 2.

To avoid this confusion, add 1:

console.log(total_team.indexOf("Shubman Gill") + 1); // output: 3

Who’s going at 5th position again??? 🤔💭

In the middle of a conversation Sourav Ganguly the chairman of BCCI asked someone “Hey Who’s coming at 5th position for batting again?”

This is how it’s found out who’s coming at 5th position:

Array_Name[n]:

let player_at = total_team[4];
console.log(player_at);  //output: KL Rahul

NOTE: Remember that the indexes start from 0? that’s why I wrote 4 instead of 5.

Is KL Rahul in the team?

In the middle of a conversation Sourav Ganguly the chairman of BCCI asked again “Hey is KL Rahul in the team?”

This is how they found out it he was in the team or not.

10 .includes():

let is_He_in = total_team.includes("KL Rahul");
console.log( is_He_in ); // output: true

.includes() Takes an input and checks if the array contains that element or not. It returns

  • True if the element exists

  • False if the element does not exist

Conclusion:

Arrays are one of the most commonly used data-types in JavaScript and many other programming languages. With the help of array methods, you can efficiently perform various operations, making your code more concise and readable.

Understanding and mastering these methods is crucial for writing clean and effective code. There are numerous array methods available, each serving a unique purpose. To deepen your knowledge, explore the MDN documentation for detailed explanations and examples.

However, theory alone isn't enough—practice is key! The best way to learn is by writing code yourself. So, grab a cup of coffee, take a sip, and start coding! 🚀