Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

JavaScript Array Methods

Last Updated on August 3, 2023 by Mayank Dham

JavaScript Arrays are powerful data structures that allow developers to store and manage collections of elements efficiently. They can hold various data types, including numbers, strings, objects, and even other arrays. Arrays are widely used in web development to handle data manipulation, iteration, and transformation tasks. Understanding array methods is essential for optimizing code and making it more readable.

How to create JavaScript Arrays ?

There are two primary methods for creating arrays in JavaScript:

1. Using an Array Literal
An array literal, represented by square brackets ([]), is the simplest and most common way to create an array.

const fruits = ['apple', 'banana', 'orange'];

2. Using the new Keyword:
Although less common, you can also create an array using the new keyword and the Array constructor.

const numbers = new Array(1, 2, 3, 4, 5);

It is generally recommended to use array literals, as they are more concise and familiar to developers.

Accessing Elements in a JavaScript Array

Arrays use zero-based indexing, which means the first element is at index 0, the second at index 1, and so on. You can access elements in an array using square brackets and the index of the element you want to retrieve.

const colors = [‘h’,’e’,’l’,’l’,’o’];

console.log(colors[0]); 
console.log(colors[1]); 

Output

h
e

Adding and Modifying Elements in JavaScript Array

You can add elements to an array or modify existing ones using their indices.

const animals = ['dog', 'cat'];

// Adding elements
animals[2] = 'elephant'; // ['dog', 'cat', 'elephant']

// Modifying elements
animals[0] = 'horse'; // ['horse', 'cat', 'elephant']

Removing Elements in JavaScript Array

In JavaScript, there are several methods to remove elements from an array. You can remove elements from the beginning, end, or at any specific index in the array. Let’s explore these methods:

1. Removing Elements from the End of the Array:

const fruits = ['apple', 'banana', 'orange'];

const removedFruit = fruits.pop();
console.log(removedFruit); 
console.log(fruits); 

Output Explanation
The pop() method removes the last element, "orange" from the fruits array and returns the removed element, which is assigned to the removedFruit variable. The array fruits now contains the elements ['apple', 'banana'].

2. Removing Elements from the Beginning of the Array:

const colors = ['red', 'green', 'blue'];

const removedColor = colors.shift();
console.log(removedColor); // Output: "red"
console.log(colors); // Output: ['green', 'blue']

Output Explanation:

The shift() method removes the first element "red" from the colors array and returns the removed element, which is assigned to the removedColor variable. The array colors now contains the elements ['green', 'blue'].

3. Removing Elements from a Specific Index:

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

numbers.splice(2, 1); // Remove 1 element starting from index 2
console.log(numbers); // Output: [1, 2, 4, 5]

Output Explanation:

The splice() method is used to remove elements from the numbers array. It starts at index 2 and removes 1 element (the element with value 3). The resulting array is [1, 2, 4, 5].

4. Removing Multiple Elements from a Specific Index:

const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

fruits.splice(1, 3); // Remove 3 elements starting from index 1
console.log(fruits); // Output: ['apple', 'kiwi']

Output Explanation:

The splice() method is used to remove multiple elements from the fruits array. It starts at index 1 and removes 3 elements ("banana", "orange", and "mango"). The resulting array is ['apple', 'kiwi'].

5. Removing Elements Based on a Condition:

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

const filteredNumbers = numbers.filter((number) => number !== 3);
console.log(filteredNumbers); // Output: [1, 2, 4, 5]

Output Explanation:
The filter() method is us
ed to create a new array filteredNumbers that includes all elements from the numbers array except for the element with value 3. The resulting array is [1, 2, 4, 5].

Note: The original array numbers remains unchanged as we used the filter() method to create a new array with the filtered elements.

How to Modify Array using JavaScript Array Methods

JavaScript provides several built-in methods for efficiently manipulating arrays. Here is a list of all of the JavaScript Array methods.

Method Description
concat() joins two or more arrays and returns a result
indexOf() searches an element of an array and returns its position
find() returns the first value of an array element that passes a test
findIndex() returns the first index of an array element that passes a test
forEach() calls a function for each element
includes() checks if an array contains a specified element
push() adds a new element to the end of an array and returns the new length of the array
unshift() adds a new element to the beginning of an array and returns the new length of the array
pop() removes the last element of an array and returns the removed element
shift() removes the first element of an array and returns the removed element
sort() sorts the elements alphabetically in strings and in ascending order
slice() selects the part of an array and returns the new array
splice() removes or replaces existing elements and/or adds new elements

JavaScript Array Example Using JavaScript Array Methods

// Creating an array
let fruits = [‘apple’, ‘banana’, ‘orange’, ‘mango’, ‘kiwi’];

// Adding elements to the end of the array
fruits.push(‘strawberry’, ‘grape’);
console.log(fruits); // Output: [‘apple’, ‘banana’, ‘orange’, ‘mango’, ‘kiwi’, ‘strawberry’, ‘grape’]

// Adding elements to the beginning of the array
fruits.unshift(‘pear’, ‘pineapple’);
console.log(fruits); // Output: [‘pear’, ‘pineapple’, ‘apple’, ‘banana’, ‘orange’, ‘mango’, ‘kiwi’, ‘strawberry’, ‘grape’]

// Removing the last element from the array
const removedFruit1 = fruits.pop();
console.log(removedFruit1); // Output: "grape"
console.log(fruits); // Output: [‘pear’, ‘pineapple’, ‘apple’, ‘banana’, ‘orange’, ‘mango’, ‘kiwi’, ‘strawberry’]

// Removing the first element from the array
const removedFruit2 = fruits.shift();
console.log(removedFruit2); // Output: "pear"
console.log(fruits); // Output: [‘pineapple’, ‘apple’, ‘banana’, ‘orange’, ‘mango’, ‘kiwi’, ‘strawberry’]

// Removing elements from a specific index
fruits.splice(2, 2); // Remove 2 elements starting from index 2
console.log(fruits); // Output: [‘pineapple’, ‘apple’, ‘kiwi’, ‘strawberry’]

// Removing elements based on a condition
const filteredFruits = fruits.filter((fruit) => fruit.length > 4);
console.log(filteredFruits); // Output: [‘pineapple’, ‘strawberry’]

// Mapping elements to a new array
const upperCaseFruits = fruits.map((fruit) => fruit.toUpperCase());
console.log(upperCaseFruits); // Output: [‘PINEAPPLE’, ‘APPLE’, ‘KIWI’, ‘STRAWBERRY’]

Conclusion
JavaScript array methods are crucial tools for working with arrays efficiently. They provide powerful ways to manipulate, iterate, and transform arrays, making it easier to perform various tasks in web development. By mastering these array methods, you can write cleaner, more concise, and more expressive code, enhancing your JavaScript skills and productivity significantly. Understanding and utilizing array methods will undoubtedly elevate your proficiency as a JavaScript developer.

Frequently Asked Questions (FAQs)

Here are some of the most frequently asked questions about JavaScript Array Methods.

Q1: What are JavaScript array methods?
JavaScript array methods are built-in functions that can be applied to arrays to perform various operations like adding, removing, and manipulating elements, as well as iterating over the array. These methods simplify the process of working with arrays and make it easier to perform common tasks efficiently.

Q2: How to create array methods in JavaScript?
In JavaScript, you can create custom array methods by adding new functions to Array.prototype`. This way, the newly defined method will be available to all arrays in your code.

Q3: How to add methods in an array in JavaScript?
To add methods to an existing array in JavaScript, you can directly assign a function to a property of the array object. Here’s an example of adding a method called print to an array:

const fruits = ['apple', 'banana', 'orange'];

fruits.print = function() {
  console.log(this.join(', '));
};

fruits.print(); 

Q4: How many methods are there in JavaScript?
JavaScript provides a variety of built-in array methods to work with arrays. As of my knowledge cutoff in September 2021, there are over 30 array methods in JavaScript. Some of the commonly used array methods include push(), pop(), shift(), unshift(), slice(), splice(), concat(), indexOf(), find(), filter(), map(), reduce(), and many more. However, it’s important to note that the number of array methods can change over time as JavaScript evolves with new ECMAScript specifications. Always refer to the latest documentation for the most up-to-date list of array methods in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *