Array Methods in JavaScript

Array Methods in JavaScript

An array is a special variable in all the languages that are used to store different elements. JavaScript array contains some built-in properties. We can use them to add, remove, iterate, or manipulate data as per our requirements.JavaScript array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

Declaration of an Array: There are two ways to declare an array.

Syntax:

let arrayName = [value1, value2, ...]; 
let arrayName = new Array();

JavaScript Array Methods:

1.JavaScript Array length

This length property in javascript returns the number of array elements in the array.

Syntax:

arr.length

Example:

let name = ["hitesh sir","anurag sir"];
let len = name.length;
console.log(len);

let arr = ["name", 44];
console.log(arr.length);

Output:

2
2

2.JavaScript Array reverse()

This reverse property in javascript returns the array in reverse order.

Syntax:

arr.reverse()

Example:

let arr = [1, 2, 3, 4, 5];
let reversedArray = arr.reverse();
console.log(reversedArray);

Output:

[ 5, 4, 3, 2, 1 ]

2.JavaScript Array sort()

This sort property in javascript returns the array items in a specific order (ascending or descending).

Syntax:

arr.sort()

Example:

var names = ["jayanth","sandeep","gopi"];
names.sort();
console.log(names);

var num = [5,4,3,2,1];
num.sort();
console.log(num)

Output:

['gopi','jayanth','sandeep']
[1,2,3,4,5]

3.JavaScript Array fill()

The fill property in javascript returns an array by filling all the elements with the specified value.

Syntax:

arr.fill(value,start,end)

fill() Parameters

The fill() method contains 3 parameters:

  • value - Value to fill the array with.

  • start - Start index (default is 0).

  • end - End index (default is array size), which is always excluded.

Example:

var names = ["jayanth","sandeep","gopi"];
names.fill(suresh);
console.log(names);

var num = [5,4,3,2,1];
num.fill(2,1,3);
console.log(num)

Output:

['suresh','suresh','suresh']
[5,2,2,2,1]

4.JavaScript Array join()

The join() method returns a new string by concatenating all of the elements in an array, separated by a specified separator.

Syntax:

arr.join(separator)

join() Parameter

The join() method contains a single parameter:

  • separator: A string to separate each pair of adjacent elements of the array.(default-comma)

Example:

let message = ["JavaScript", "is", "fun."];
let joinedMessage = message.join(" ");
console.log(joinedMessage);

let msg = ["Sainadh", "Gopi" , "Kundan"];
let joinedmsg = msg.join("|");
console.log(joinedmsg);

Output:

JavaScript is fun.
Sainadh|Gopi|Kundan

5.JavaScript Array toString()

The toString() method returns a string by using the elements of the given array.

Syntax:

arr.toSting()

Example:

let message = ["JavaScript", "is", "fun."];
let msg_str = message.toString();
console.log(msg_str);

let msg = ["Sainadh", "Gopi" , "Kundan"];
let msg_str1 = msg.toString();
console.log(msg_str1);

Output:

JavaScript,is,fun.
Sainadh,Gopi,Kundan

6.JavaScript Array pop()

The pop() method removes the last element from an array and returns the deleted element from the array.

Syntax:

arr.pop()

Example:

let message = ["JavaScript", "is", "fun."];
let msg_str = message.pop();
console.log(msg_str);

Output:

fun.

7.JavaScript Array shift()

The shift() method removes the first element from an array and returns the deleted element from the array.

Syntax:

arr.shift()

Example:

let message = ["JavaScript", "is", "fun."];
let msg_str = message.shift();
console.log(msg_str);

Output:

JavaScript

8.JavaScript Array push()

The push() method adds the element to the existing array at the end of the array.

Syntax:

arr.push()

Example:

let message = ["JavaScript", "is", "fun"];
let msg_str = message.push("complex");
console.log(message);

Output:

["JavaScript", "is", "fun","complex"]

8.JavaScript Array concat()

The concat() method returns a new array by adding two (or) more arrays.

Syntax:

arr.concat()

Example:

let message = ["JavaScript", "is", "fun"];
let num=[1,2,3,4];
let msg_str = message.concat(num);
console.log(msg_str);

Output:

["JavaScript", "is", "fun",1,2,3,4]

9.JavaScript Array splice()

The splice() method modifies an array (adds, removes or replaces elements).

Syntax:

arr.splice(start, deleteCount, item1, ..., itemN)

Example:

let prime_numbers = [2, 3, 5, 7, 9, 11];

// replace 1 element from index 4 by 13
let removedElement = prime_numbers.splice(4, 1, 13);
console.log(removedElement);
console.log(prime_numbers);

Output:

[ 9 ]
[ 2, 3, 5, 7, 13, 11 ]

10.JavaScript Array slice()

The slice() method returns a shallow copy of a portion of an array into a new array object.

Syntax:

arr.slice(start, end)

Example:

let numbers = [2, 3, 5, 7, 11, 13, 17];

// create another array by slicing numbers from index 3 to 5
let newArray = numbers.slice(3, 6);
console.log(newArray);

Output:

[ 7, 11, 13 ]

11.JavaScript Array map()

The map() method creates a new array with the results of calling a function for every array element.

Syntax:

arr.map(callback(currentValue), thisArg)

The map() method takes in:

  • callback - The function called for every array element. Its return values are added to the new array. It takes in:

    • currentValue - The current element being passed from the array.
  • thisArg (optional) - Value to use as this when executing callback. By default, it is undefined.

Example:

let numbers = [2, 4, 6, 8, 10];

// function to return the square of a number
function square(number) {
  return number * number;
}

// apply square() function to each item of the numbers list
let square_numbers = numbers.map(square);
console.log(square_numbers);

Output:

[ 4, 16, 36, 64, 100 ]

12.JavaScript Array filter()

The filter() method returns a new array with all elements that pass the test defined by the given function.

Syntax:

arr.filter(callback(element), thisArg)

The filter() method takes in:

  • callback - The test function to execute on each array element; returns true if element passes the test, else false. It takes in:

    • element - The current element being passed from the array.
  • thisArg (optional) - The value to use as this when executing callback. By default, it is undefined.

Example:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// function to check even numbers
function checkEven(number) {
  if (number % 2 == 0)
    return true;
  else
    return false;
}

// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);

Output:

[ 2, 4, 6, 8, 10 ]

13.JavaScript Array reduce()

The reduce() method executes a reducer function on each element of the array and returns a single output value.

Syntax:

arr.reduce(callback(accumulator, currentValue), initialValue)

The reduce() method takes in:

  • callback - The function to execute on each array element (except the first element if no initialValue is provided). It takes in

    • accumulator - It accumulates the callback's return values.

    • currentValue - The current element being passed from the array.

  • initialValue (optional) - A value that will be passed to callback() on first call. If not provided, the first element acts as the accumulator on the first call and callback() won't execute on it.

Example:

 const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);

console.log(sum);

Output:

15