Loading...

JavaScript Array Methods:

JavaScript Array Methods:

JavaScript arrays method are a very powerful data structure, and you can perform a variety of operations on them using a wide range of built-in methods. Hello everyone, In this blog post, we will take a look at some of the most useful array methods in JavaScript and how you can use them in your code. We will go into more detail on each method and discuss them with examples.

JavaScript Array Methods

Arrays are one of the most common things you are going to use as a programmer. So if you want to get better at JavaScript, well arrays are an essential part of JavaScript. These arrays come with a lot of features that can make complex things much easier. Here are some of the most common array methods ‘push()’, `unshift()`, pop(), shift(), slice(), etc. We will discuss them in detail in the upcoming sections.

Features of JavaScript Array methods

JavaScript array methods are functions that can perform various operations on arrays. Some key features of this method include.

  • Modify the original array: some array methods such as pop, push, shift, and slice modify the original array and return the modified array.
  • Return a new array: Other array methods, such as Concat, Slice, and Map, return a new array without modifying the original array.
  • Accept arguments: Many array methods accept arguments that allow you to customize their behaviour. For example, the.slice() method accepts start and end indices as arguments, and the .sort() method accepts a comparison function as an argument.

Basic Array Methods

JavaScript Array.push() Method

Using the push function, we can add multiple objects at the end of an array. It modifies the original array and prints the new array’s length.

Syntax:

array.push(element1, element2, ...)
Code language: JavaScript (javascript)

Let’s understand this through an example

// Declaring the array prime const prime = [2, 3, 5]; // push prime.push(7, 11); // Now the prime array contains [2, 3, 5, 7, 11] console.log(prime) // // To find the length declare a new function const num = prime.push(); console.log(num);
Code language: JavaScript (javascript)

output:

[2, 3, 5, 7, 11] 5
Code language: Bash (bash)

JavaScript Array.unshift() Method

It’s the same as the push function. We can add new items to the array. But the difference is that added items will not add at the end, instead they will get added at the start of the array.

Syntax:

array.unshift(element1, element2 , ...)
Code language: JavaScript (javascript)

In this example, we will be including 2 and 3 at the start of the prime array

const prime = [5, 7, 11]; // unshift prime.unshift(2, 3); // Now the prime array contains [2, 3, 5, 7, 11] console.log(prime);
Code language: JavaScript (javascript)

output:

[2, 3, 5, 7, 11]
Code language: Bash (bash)

JavaScript Array.pop() Method

pop is used to remove the last element present in the array, contrary to the push method. And it also returns the last element present in the array.

Syntax:

array.pop() // No parameter
Code language: JavaScript (javascript)
const prime = [2, 3, 5, 7, 9] prime.pop(); // Removes 9 console.log(prime); // prime contains [2, 3, 5, 7] const last = prime.pop(); //Returns the last element console.log(last);
Code language: JavaScript (javascript)

output:

[2, 3, 5, 7] 7
Code language: Bash (bash)

JavaScript Array.shift() Method

It is the opposite of unshift method. Using this method, we can remove the elements from the starting of the array.

Syntax:

array.shift() // No Parameter
Code language: JavaScript (javascript)
// Example const prime = [1, 2, 3, 5, 7] prime.shift(); // Removes 1 console.log(prime); // prime contains [2, 3, 5, 7] const first = prime.shift(); // Returns the first element console.log(first);
Code language: JavaScript (javascript)

output:

[ 2, 3, 5, 7 ] 2
Code language: Bash (bash)

JavaScript Array.splice() Method

This method performs various operations like removing and adding elements from where ever you want to, not just limited to start and end.

Syntax:

array.splice(start, delete, element1, element2, ..)
Code language: JavaScript (javascript)

Parameters

  • start – At which index position do you want to start the operation? Make sure you get familiar with the zero indexing method.
  • delete – How many elements do you want to delete? If you don’t want to delete any, then mention 0
  • At last, you can add the elements you want to add to the array

Let’s understand this through an example

const prime = [2, 3, 4, 5, 7] /* Here i want to delete the 4 which is present at 2rd postion And want to delete only 4 so the delete count is 1*/ prime.splice(2, 1); console.log(prime); // Now prime contains [2, 3, 5, 7] // To add 11, 13 at last prime.splice(4, 0, 11, 13); console.log(prime);
Code language: JavaScript (javascript)

output:

[ 2, 3, 5, 7 ] [ 2, 3, 5, 7, 11, 13]
Code language: Bash (bash)

All these methods work for strings as well. For example

const name = ["code", "damn", "start"] name.push("up", "frontend"); console.log("After push operation: " + name); // name = code, damn, start, up, frontend name.unshift("hello"); console.log("After unshift operation: " + name); // name = hello, code, damn, start, up, frontend name.pop(); console.log("After pop operation: " + name); // name = hello, code, damn, start, up name.shift(); console.log("After shift operation: " + name);
Code language: JavaScript (javascript)

output:

After push operation: code,damn,start,up,frontend After unshift operation: hello,code,damn,start,up,frontend After pop operation: hello,code,damn,start,up After shift operation: code,damn,start,up
Code language: Bash (bash)

Converting Arrays to Strings

JavaScript Array length

The length property is used to calculate the number of arrays present in the array. It automatically modifies the array length

// Example const strings = ["code", "damn", "web3"]; console.log(strings.length); // 3 strings.push("web2"); console.log(strings.length); // 4 strings.pop(); strings.pop(); console.log(strings.length) // 2
Code language: JavaScript (javascript)

JavaScript Array.reverse() Method

As the name itself suggest, this method is used to reverse the original array and modify it. Let’s take the same example, of prime numbers.

Syntax:

array.reverse()
Code language: JavaScript (javascript)
// Example const prime = [2, 3, 5, 7]; prime.reverse(); console.log(prime);
Code language: JavaScript (javascript)

output:

[7, 5, 3, 2]
Code language: Bash (bash)

JavaScript Array.sort() Method

The sort() method is used to sort the array in ascending order for numbers and in alphabetical order for strings, this is the default way. You can sort it in whatever way you like.

const num = [5, 7, 2, 4, 8]; num.sort(); console.log(num); const string = ["code", "startup", "damn", "frontend"] string.sort(); console.log(string);
Code language: JavaScript (javascript)

output:

[ 2, 4, 5, 7, 8 ] [ 'code', 'damn', 'frontend', 'startup' ]
Code language: Bash (bash)

JavaScript Array.fill() Method

Using the fill() operation, we can replace certain elements with some static values. This method is an in-place method, meaning that it modifies the original array. It does not return a new array.

Syntax:

array.fill(value, start, end)
Code language: JavaScript (javascript)

parameters

  • value – The static value which you want to fill in the array
  • start – The value of the index from where you want to replace the array
  • end – The last value of the index
const nums = [1, 2, 3, 5, 6]; nums.fill(0); // fills the entire array with 0 console.log(nums); const strings = ["code", "damn", "web2", "web3"]; strings.fill("abc", 2, 4); // fills the elements with abc at index 2 and 3 console.log(strings);
Code language: JavaScript (javascript)

output:

[ 0, 0, 0, 0, 0 ] [ 'code', 'damn', 'abc', 'abc' ]
Code language: Bash (bash)

JavaScript Array.join() Method

The join() method is used to join all the elements of an array into a single string. It takes an optional separator string as an argument, which is used to separate the elements of the array in the resulting string. If the separator is not specified, the elements are separated with a comma. Here is an example of using the join() method:

const strings = ["code", "damn", "web2", "web3"]; const joined = strings.join('-'); // All the strings are joined by an - console.log(joined); const nums = [1, 2, 3, 5, 6]; const joined_nums = nums.join(); // sperator is not mentioned by default it takes , console.log(joined_nums);
Code language: JavaScript (javascript)

output:

code-damn-web2-web3 1,2,3,5,6
Code language: Bash (bash)

JavaScript Array.concat() Method

We can add two or more arrays using this method. This operation doesn’t change the original array, but instead returns a new array that contains the values of the joined arrays.

Here is an example to add two array

const strings = ["code", "damn", "web3"]; const nums = [1, 2, 3]; const mergedarray1 = strings.concat(nums); console.log(mergedarray1); // We can add multiple arrays also const int = [-1, 0, 1]; const mergedarray2 = strings.concat(nums, int); console.log(mergedarray2);
Code language: JavaScript (javascript)

outputs:

[ 'code', 'damn', 'web3', 1, 2, 3 ] [ 'code', 'damn', 'web3', 1, 2, 3, -1, 0, 1 ]
Code language: JavaScript (javascript)

JavaScript Array.indexof() Method

This method is used to find the index of the specified element, which is present in the array. If the element is not found, the method returns -1.

const strings = ["code", "damn", "web3"]; console.log(strings.indexOf('damn')); // 1 console.log(strings.indexOf('hello')); // -1
Code language: JavaScript (javascript)

If there are multiple items with the same name or same number then you can specify the index from where you want to start searching that element. In case the index is not specified it just outputs the first index where it finds the mentioned item.

const nums = [2, 3, 5, 3]; console.log(nums.indexOf(3, 2)); // 3 console.log(nums.indexOf(3)); // 1
Code language: JavaScript (javascript)

JavaScript Array.lastindexof() Method

Like the indexof() method, the last indexof() method is used to find the specified element. But it starts searching from the last. Once it is found, it returns the index.

const strings = ["code", "damn", "web3", "web2"]; console.log(strings.lastIndexOf("web2")); //3
Code language: JavaScript (javascript)

JavaScript Array.find() Method

The find() the method returns the value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

Here is an example of using the find() method:

const numbers = [4, 9, 16, 25]; const first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; } console.log(first); // 25
Code language: JavaScript (javascript)

JavaScript Array.filter() Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Here is an example of using the filter() method:

const strings = ["codedamn", "Hello", "Startup", "Web"]; const longwords = strings.filter(word => word.length > 6); console.log(longwords);
Code language: JavaScript (javascript)

output:

[ 'codedamn', 'Startup' ]
Code language: Bash (bash)

Javascript Array .map() Method

map() the method creates a new array populated with the results of calling a provided function on every element in the calling array.

Here is an example of using the map() method:

const num = [2, 3, 4, 5]; // pass a function to map const square = num.map(x => x * x); console.log(square);
Code language: JavaScript (javascript)

output:

[ 4, 9, 16, 25 ]
Code language: Bash (bash)

JavaScript Array.slice() Method

slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included). The original array will not be modified.

Here is an example of using the slice() method:

const animals = ["lion", "tiger", "elephant", "deer"]; console.log(animals.slice(2)); // excepted output: [elephant, deer] console.log(animals.slice(1, 3)); // expected output: [tiger, elephant]
Code language: JavaScript (javascript)

JavaScript Array.includes() Method

includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Let’sLets take the same example of animals

const animals = ["lion", "tiger", "elephant", "deer"]; console.log(animals.includes('tiger')); // expected output : true console.log(animals.includes('cat')); // expected output : false
Code language: JavaScript (javascript)

JavaScript Array.reduce() Method

The reduce() the method is used to apply a function to each element in an array, resulting in a single output value. The reduce() method executes a provided function for each value of the array (from left to right), and the return value of the function is used in the next call to the function.

Here’s an example of using the reduce() method to sum all the elements in an array:

const numbers = [1, 2, 3, 4]; const sum = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue; }, 0); console.log(sum); // 10
Code language: JavaScript (javascript)

In this example, the reduce() the method takes a function with two arguments: accumulator and currentValue. The accumulator is the total value returned by the function so far and currentValue is the current element being processed in the array. The reduce() method also takes an optional second argument, which is the initial value of the accumulator.

The reduce() the method is often used to perform some kind of computation on an array and reduce it to a single value. It can be used to implement a wide variety of algorithms, such as calculating the product of all the elements in an array or finding the shortest string in an array of strings.

conclusion

In conclusion, the JavaScript Array object has a variety of useful methods that can be used to manipulate and transform arrays. These methods include the map(), filter(), reduce(), and sort() methods, which allow for the creation of new arrays based on the elements of an existing array, as well as the push(), pop(), shift(), and unshift() methods, which allow for the addition and removal of elements from an array.

It’s a lot of stuff to remember, right? Well, don’t mug up these methods. Frequently use them whenever required you will automatically remember them. By utilizing these methods, developers can more easily and efficiently work with arrays in their code

Frequently Asked Question

What are JavaScript array methods?

JavaScript array methods are actions that can be performed on arrays to manipulate them in various ways such as iterating over the elements, adding or removing elements, and transforming the elements. Some of the common array methods are included in the article you can read more about them.

What are array methods?

Array methods are actions that can be performed on arrays to manipulate them in various ways such as iterating over the elements, adding or removing elements, and transforming the elements. Array methods are functions that are associated with arrays and can be called on an array object.

How to write array methods in JavaScript?

To write an array method in JavaScript, you can define a function that performs the desired operation on the array and then uses the prototype property to add the function as a method to the Array object.

Which of the following are the methods of the array in JavaScript?

There are many other methods available for the Array object in JavaScript. In this article, you can find detailed information about them.

How do array methods work?

Array methods are functions that can be called on arrays to perform some operation on the array or to retrieve some information about the array. Array methods are called on the array object and typically use the . notation, like this: array.method().

Sharing is caring

Did you like what Thrishank wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: