Array Methods in JavaScript

Array Methods in JavaScript

Why Arrays?

Suppose you have a list of items, storing them in single variables could look as shown below, let's take an example of company names, here we need to create three variables to store the name of three companies.

let com_name_1 = "ineuron";
let com_name_2 = "lco";
let com_name_3 = "Learnyst";

What if we want to store more than three companies' names, let's just say the list of all the top Edtech companies, there could be 100 to 500 companies! and what if we want to do some sort of operation like (searching, or sorting) to find a specific company, we can't do all those operations in the method shown above. So in that case our life saver is arrays.


Array

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an array

There are two ways to create an array

  • Using array literal
  • Using new keyword

Array literal [ ]

Using array literal is the easiest way to create an array in javascript.

Syntax:

const array_name = [item1, item2, ...];

It is a common practice to declare arrays with the const keyword. the const keyword makes sure that an array declared with const cannot be reassigned as shown below.

const com_name = ["lco", "ineuron", "findcoder"];
com_name = ["blogs", "codercommunity", "hitesh"];    // ERROR

But we can reassign the elements in an array :

// You can create a constant array:
const com_name  = ["lco", "ineuron", "findcoder"];

// You can change an element:
com_name[0] = "blogs";

// You can add an element:
com_name.push("hitesh");
console.log(com_name);

Output:
[ blogs, ineuron, findcoder, hitesh ]

Using the new keyword

We can also create an array as shown below.

Syntax:

const com_name = new Array("lco", "ineuron", "findcoder");

The two examples above do exactly the same. There is no need to use new Array(). For simplicity, readability and execution speed, we use the array literal method.

Accessing Array Element

We access an array element by referring to the index number as shown.

index.png

const com_name = ["lco", "ineuron", "findcoder"];
let com_name_1 = com_name[0];
console.log(com_name_1);

Output:
lco

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing array element

const com_name = ["lco", "ineuron", "findcoder"];
com_name[0] = "blogs";
console.log(com_name);

Output:
[ 'blogs', 'ineuron', 'findcoder ]

Access the Full Array

In javascript full array name can be accessed by referring to the array name as shown below.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name);

Output:
[ 'lco', 'ineuron', 'findcoder' ]

Array Properties and Methods

The real power of the JavaScript arrays is the built-in array properties and methods.

length()

The length property of an array returns the number of array elements present in it as shown.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.length);

Output:
3

Sort()

The sort property of an array will sort the element present in it as shown.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.sort());

Output:
[ 'findcoder', 'ineuron', 'lco' ]
const no = [7,5,2,1,4,6];
console.log(no.sort());

Output:
[ 1, 2, 4, 5, 6, 7 ]

Array Methods

Following are various kinds of array methods.

toString()

The toString() array method converts an array to a string of comma (,) separated array values as shown below.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.toString());

Output:
lco,ineuron,findcoder

join()

The join() method also joins all array elements into a string. It works just like toString(), but in addition, we can specify the separator as shown in the example given below.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.join("|"));
console.log(com_name.join("*"));

Output:
lco|ineuron|findcoder
lco*ineuron*findcoder

pop()

The pop() method removes the last element of an array.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.pop()); // returns the removed element
// array after pop() method
console.log(com_name);

Output:
findcoder
[ 'lco', 'ineuron' ]

push()

The push() method adds a new element at the end of an array and in addition to that, it also returns the final length of the array after the pushing operation as shown below.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.push("codercommunity")); // array length after adding element at the and
//array after pushing method
console.log(com_name);

Output:
4
[ 'lco', 'ineuron', 'findcoder', 'codercommunity' ]

One easier way to add an element at the end is by using the length property of the array as shown.

const com_name = ["lco", "ineuron", "findcoder"];
com_name[com_name.length] = "hitesh"; 
console.log(com_name);

Output:
[ 'lco', 'ineuron', 'findcoder', 'hitesh' ]

shift()

The shift() method removes the first array element and "shifts" all other elements to a lower index and returns the value that was "shifted out" as shown below.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.shift()); // removes the first array element
//array after shifting 
console.log(com_name);


Output:
lco
[ 'ineuron', 'findcoder' ]

unshift()

The unshift() method adds a new element at the beginning of an array, and "unshifts" older elements as shown below. In addition to that, it also returns the final length of the array.

const com_name = ["lco", "ineuron", "findcoder"];
console.log(com_name.unshift("hitesh")); // added hitesh at the beginning and return the final length
//array after unshifting 
console.log(com_name);

Output:
4
[ 'hitesh', 'lco', 'ineuron', 'findcoder' ]

Merging arrays

concat()

The concat() method creates a new array by merging (concatenating) the existing arrays.

const com_name_1 = ["lco", "ineuron", "findcoder"];
const com_name_2 = ["uipicker", "blogs", "codercommunity"];
const com_name_3 = com_name_1.concat(com_name_2);
console.log(com_name_3);

Output:
[
  'lco',
  'ineuron',
  'findcoder',
  'uipicker',
  'blogs',
  'codercommunity'
]

The concat() method does not change the existing arrays. It always returns a new array and can merge any number of arrays.

Merging two arrays

const com_name_1 = ["lco", "ineuron", "findcoder"];
const com_name_2 = ["uipicker", "blogs", "codercommunity"];
const com_name_3 = com_name_1.concat(com_name_2);
console.log(com_name_3);
// original arrays
console.log(com_name_1);
console.log(com_name_2);

Output:
[
  'lco',
  'ineuron',
  'findcoder',
  'uipicker',
  'blogs',
  'codercommunity'
]
[ 'lco', 'ineuron', 'findcoder' ]
[ 'uipicker', 'blogs', 'codercommunity' ]

Merging three arrays

const com_name_1 = ["lco", "ineuron", "findcoder"];
const com_name_2 = ["uipicker", "blogs", "codercommunity"];
const com_name_3 = ["hitesh","anurag","anirudh"]
const com_name_4 = com_name_1.concat(com_name_2,com_name_3);
console.log(com_name_4);

Output:
[
  'lco',
  'ineuron',
  'findcoder',
  'uipicker',
  'blogs',
  'codercommunity',
  'hitesh',
  'anurag',
  'anirudh'
]

concat() method can also take strings as an arguments.

const com_name_1 = ["lco", "ineuron", "findcoder"];
const new_name = com_name_1.concat("hitesh");
console.log(new_name);

Output:
[ 'lco', 'ineuron', 'findcoder', 'hitesh' ]

splice()

The splice() method can be used to add new items to an array.

Syntax:

splice.(Target_index, How_many_values_to_modify, New_values);
const com_name_1 = ["lco", "ineuron", "findcoder","codercommunity"];
let removed_element = console.log(com_name_1.splice(1, 1, "hitesh")); //return removed element
console.log(com_name_1);

Output:
[ 'ineuron' ]
[ 'lco', 'hitesh', 'findcoder', 'codercommunity' ]

slice()

The slice() method cut out a part of an array into a new array. If the end argument is skipped, the slice() method slices out the rest of the array.

Syntax:

slice.(target_index, ending_index) //not including the ending_index
const com_name_1 = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name_1.slice(1)); //new sliced array
console.log(com_name_1); // original array

Output:
[ 'ineuron', 'findcoder', 'codercommunity' ]
[ 'lco', 'ineuron', 'findcoder', 'codercommunity' ]
const com_name_1 = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name_1.slice(1, 3)); //new sliced array

Output:
[ 'ineuron', 'findcoder' ]

The slice() method creates a new array and does not remove any elements from the source array as shown below.

const com_name_1 = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name_1.slice(1, 3)); //new sliced array
// original array
console.log(com_name_1);

Output:
[ 'ineuron', 'findcoder' ]
[ 'lco', 'ineuron', 'findcoder', 'codercommunity' ]

copyWithin()

The copyWithin() method copies array elements to another position in the array. This method overwrites the existing values and does not add items to the array. This method returns the changed array.

Syntax:

array.copyWithin(target, start, end) // Not including end index

Parameters

Target: Required, the index position to copy the elements to.
Start: Optional, the start index position, Default is 0.
end: Optional, the end index position. Default is the array length.

const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.copyWithin(1));

Output:
[ 'lco', 'lco', 'ineuron', 'findcoder' ]

Note that only the target index is given so this will start copying at index 1 ("ineuron"), as the default value for start is index 0 so this will copy from index 0 ("lco") and continue till the length of the array, as the default value for the end is the length of the array.

const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.copyWithin(1, 2));

Output:
[ 'lco', 'findcoder', 'codercommunity', 'codercommunity' ]
const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.copyWithin(1, 2 ,3));  // Not including the index 3

Output:
[ 'lco', 'findcoder', 'findcoder', 'codercommunity' ]

Note that the end index is not included this will copy from index 2 to index 2 only.

fill()

The fill() method fills specified elements in an array with a value and overwrites the original array. The start and end position can be specified. If not, all elements will be filled as shown below.

Syntax:

array.fill(value, start, end)

Parameters

Value: Required, value to fill in.
Start: Optional, the start index, default is 0.
end: Optional, the stop index, default is array length.

const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.fill("hitesh"));

Output:
[ 'hitesh', 'hitesh', 'hitesh', 'hitesh' ]

Here no start and end position is given so this will fill the whole array.

fill() with start and end parameters.

const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.fill("hitesh", 2,4));  // fills "hitesh" from index 2 to 3

Output:
[ 'lco', 'ineuron', 'hitesh', 'hitesh' ]

includes()

The includes() method returns true if an array contains a specified value and returns false if the value is not found. This method is case-sensitive.

Syntax:

array.includes(element, start)

Parameters

element: Required, the value to search for.
start: Optional, start position, default is 0.

const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.includes("ineuron"));

Output:
true
const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.includes("ineuron", 2));  // starts from index 2

Output:
false

indexOf()

The indexOf() method returns the first index (position) of a specified value and returns -1 if the value is not found. This method starts at a specified index and searches from left to right. By default, the search starts at the first element and ends at the last. Negative start values counts from the last element (but still searches from left to right).

Syntax:

array.indexOf(item, start)

Parameters

item: Required, to find the index of.
start: Optional, from where to start the search, the default value is 0. Negative values start the search from the end of the array.

const com_name = ["lco", "ineuron", "findcoder","codercommunity"];
console.log(com_name.indexOf("findcoder"));

Output:
2

lastIndexOf()

The lastIndexOf() method returns the last index (position) of a specified value and returns -1 if the value is not found. The lastIndexOf() starts at a specified index and searches from right to left. By default, the search starts at the last element and ends at the first. Negative start values counts from the last element (but still searches from right to left).

Syntax:

array.lastIndexOf(item, start)

Parameters

item: Required, the value to search for
start: Optional, from where to start the search, the default is the last element (array.length-1). Negative values start the search from the end of the array.

const com_name = ["lco", "ineuron", "findcoder","lco","codercommunity"];
console.log(com_name.lastIndexOf("lco"));

Output:
3

map()

The map() creates a new array by calling a function for every array element. It calls a function once for each element in an array and does not execute the function for empty elements. It does not modify the original array.

const no = [1,4,9,16];
console.log(no.map(Math.sqrt));

Output:
[ 1, 2, 3, 4 ]

reverse()

The reverse() method reverses the order of the elements in an array. this method overwrites the original array.

Syntax:

array.reverse()
const no = [1,4,9,16];
console.log(no.reverse());

Output:
[ 16, 9, 4, 1 ]

Summary

An array is a collection of data items (same or different) stored under a single variable name. Array uses index-based access. The index always starts with 0. For insertion of element we use push() & unshift() method whereas for deletion we use pop() & shift() method. Some methods to create an array are using Array constructor, Array.of(), Array.from(), and the spread operator(... ) Array.isArray(value) is used to determine if the passed value is an array or not.

ย