JavaScript Arrays and Its Methods!!!

This is complete guide about Array and its methods in JavaScript.

JavaScript Arrays and Its Methods!!!

Check out my Git hub for latest projects

Git Hub

Also check out my profile on findcoder.io

Pramod Reddy Pandiri

Intro

In Programming, Array is collection of similar or dissimilar elements .We can store and retrieve when needed

I think every programming language has Array data structure , may be with different name but same behaviour.Generally arrays are treated as Objects.

Array object has Constructor,Static Methods, Static Properties,Instance methods,Instance Properties.In this article we are gonna cover almost of those.

What is an Array in JavaScript?

A pair of square brackets [] represents an array in JavaScript. All the elements in the array are comma(,) separated.

In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays.

Here is an example of an array with four elements: type Number, Boolean, String, and Object.

 const mixedTypedArray = [100, true, 'pramod', {}];

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, 'pramod' 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!!!

Array() Constructor

Array constructor is used to create array Objects.

 var arrayName = new Array(element1 ,element2, element2......);

new creates a new instance of array object.

Example : General and easy ways to create an array

 let names=['steve rogers','tony stark','bruce','natasha ','wanda '];

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.

let eleFromArray = names[0]; //names[index]
// output : "steve rogers"

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

for(let i=0; i<names.length; i++) {
  console.log(`Element at index ${i} is ${names[i]}`);
};
//output:
  Element at index 0 is steve rogers
 Element at index 1 is tony stark
 Element at index 2 is bruce
 Element at index 3 is natasha
 Element at index 4 is wanda

How to Add Elements to an Array in JS

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 characters to the names array, like this:

 let names=['steve rogers','tony stark','bruce','natasha ','wanda '];
names.push("thor");
// names array now =>  ['steve rogers','tony stark','bruce','natasha ','wanda ','thor'];

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

 let names=['steve rogers','tony stark','bruce','natasha ','wanda '];
  names.unshift("thor");
// names array now =>  ['thor','steve rogers','tony stark','bruce','natasha ','wanda '];

How to Remove Elements from an Array in JS

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.

 let names=['steve rogers','tony stark','bruce','natasha ','wanda '];
names.pop()
// output: wanda
//names array now => ['steve rogers','tony stark','bruce','natasha ']

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.

 let names=['steve rogers','tony stark','bruce','natasha ','wanda '];
names.shift();
// output: steve rogers
//names array now => ['tony stark','bruce','natasha ','wanda '];

How to Copy and Clone an Array in JS

You can copy and clone an array to a new array using the slice() method. Note that the slice() method doesn't change the original array. Instead, it creates a new shallow copy of the original array.

let names=['steve rogers','tony stark','bruce','natasha ','wanda '];
 //syntax array.slice(startIndex, endIndex);
 let slicedArray=names.slice(1,4);
console.log(slicedArray)
//output: ['tony stark','bruce','natasha ']

If end index is not given it will take whole length of array

How to Determine if a Value is an Array in JS

You can determine if a value is an array using the Array.isArray(value) method. The method returns true if the passed value is an array.

Array.isArray(['steve rogers','tony stark','bruce','natasha ','wanda ']);
//return True
Array.isArray('steve');
//return Flase

Array length

array.length return length(total number of level one elements)

let names=['steve rogers','tony stark','bruce','natasha ','wanda '];
console.log(names.length);
//output: 5

How to Create, Remove, Update, and Access Arrays in JavaScript

In this section, we will learn about methods you can use to create a new array, remove elements to make the array empty, access elements, and many more.

The concat() array method The concat() method merges one or more arrays and returns a merged array. It is an immutable method. This means it doesn't change (mutate) existing arrays. Example for concat

const first = [1, 2, 3];
const second = [4, 5, 6];

const merged = first.concat(second);

console.log(merged); // [1, 2, 3, 4, 5, 6]
console.log(first); // [1, 2, 3]
console.log(second); // [4, 5, 6]

Using the concat() method we can merge more than two arrays. We can merge any number of arrays with this syntax:

array.concat(arr1, arr2,..,..,..,arrN);

example :

const first = [1, 2, 3];
const second = [4, 5, 6];
const third = [7, 8, 9];

const merged = first.concat(second, third);

console.log(merged); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

The join() array method

The join() method joins all the elements of the array using a separator and returns a string. The default separator used for joining is comma(,).

const emotions = ['1', '2', '3', '4'];

const joined = emotions.join();
console.log(joined); // "1,2,3,4"

You can pass a separator of your choice to join the elements. Here is an example of joining the elements with a custom separator:

const emotions = ['1', '2', '3', '4'];

const joined = emotions.join('/');
console.log(joined); // "1/2/3/4"

The fill() array method

The fill() method fills an array with a static value. You can change all the elements to a static value or change a few selected items. Note that the fill() method changes the original array.

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

colors.fill('black');
console.log(colors); // ["black", "black", "black"]

Here is an example where we are changing only the last two elements of the array using the fill() method:

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

colors.fill('pink', 1,3); // ["red", "pink", "pink"]

In this case, the first argument of the fill() method is the value we change with. The second argument is the start index to change. It starts with 0. The last argument is to determine where to stop filling. The max value of it could be colors.length.

The includes() array method

You can determine the presence on an element in an array using the includes() method. If the element is found, the method returns true, and false otherwise.

const names = ['tom', 'alex', 'bob', 'john'];

names.includes('tom'); // returns true
names.includes('july'); // returns false

The indexOf() array method

You may want to know the index position of an element in array. You can use the indexOf() method to get that. It returns the index of the first occurrence of an element in the array. If an element is not found, the indexOf() method returns -1.

const names = ['tom', 'alex', 'bob', 'john'];

names.indexOf('alex'); // returns 1 (alex is at index 1)
names.indexOf('rob'); // returns -1

There is another method lastIndexOf() that helps you find the index of the last occurrence of an element in the array. Like indexOf(), lastIndexOf() also returns -1 if the element is not found.

const names = ['tom', 'alex', 'bob', 'tom'];
names.indexOf('tom'); // returns 0
names.lastIndexOf('tom'); // returns 3

The reverse() array method

As the name suggests, the reverse() method reverses the elements' positions in the array so that the last element goes into the first position and the first one to the last.

const names = ['tom', 'alex', 'bob'];

names.reverse(); // returns ["bob", "alex", "tom"]

The reverse() method modifies original array.

The sort() array method

The sort() method is probably one of the most often used array methods. The default sort() method converts the element types into strings and then sorts them. The default sorting order is ascending. The sort() method changes the original array.

const names = ['tom', 'alex', 'bob'];

names.sort(); // returns ["alex", "bob", "tom"]

The splice() array method

The splice() method helps you add, update, and remove elements in an array. This method may be a bit confusing at the beginning, but once you know how to use it properly, you will get it right.

The main purpose of the splice() method is to delete elements from array. It returns an array of the elements deleted and modifies the original array. But you can add and replace elements using it as well.

To add an element using the splice() method, we need to pass the position where we want to add, how many elements to delete starting with the position, and the element to add. In the example below, we are adding an element zack at the index 1 without deleting any elements.

const names = ['tom', 'alex', 'bob'];

names.splice(1, 0, 'zack');

console.log(names); // ["tom", "zack", "alex", "bob"]

Have a look at the following example. Here we are removing one element from the index 2 (the 3rd element) and adding a new element, zack. The splice() method returns an array with the deleted element, bob.

const names = ['tom', 'alex', 'bob'];

const deleted = names.splice(2, 1, 'zack');

console.log(deleted); // ["bob"]
console.log(names); // ["tom", "alex", "zack"]

Check out my Git hub for latest projects

Git Hub

Also check out my profile on findcoder.io

Pramod Reddy Pandiri