javascript

Array Methods


 

Array methods provide powerful tools for manipulating arrays efficiently. These methods allow developers to add, remove, modify, and iterate through elements in arrays with ease.

Commonly used javascript methods are:

 

1. push(): 

It adds one or more elements to the end of an array.

 

Syntax:

Array.push(item1, item2 ...);

 

Example:

let arr = [10, 122, 32];
arr.push(20);
arr.push(234);
console.log(arr); // [ 10, 122, 32, 20, 234 ];

 

2. pop():

It removes the last element from an array.

 

Syntax:

Array.pop();

 

Example:

let arr = [23, 34, 35];
arr.pop(); // 35 removed
console.log(arr); // [ 23, 34 ]

 

3. shift():

It removes the first element from an array.

 

Syntax:

Array.shift();

 

Example:

let arr = ["php", "python", "c++", "java"];
arr.shift(); // "php" removed
console.log(arr); // ['javascript', 'c', 'php', 'python', 'c++', 'java' ];

 

4. unshift(): 

It adds one or more elements to the beginning of an array.

 

Syntax:

Array.unshift(item1, item2, ...);

 

Example:
let arr = ["php", "python", "c++", "java"];
arr.unshift("javascript", "c");
console.log(arr); // [ 'javascript', 'c', 'php', 'python', 'c++', 'java' ]

 

5. splice(): 

It adds or removes elements from an array for given index.

Note: It alters the original array.

 

Syntax:

Array.splice(start, deleteCount, item1, item2, ...);

 

Example:

let arr = ['a', 'b', 'c', 'd', 'e'];

// Removing elements from the arr starting from index 2 (inclusive) and removing 2 elements
let removedElements = arr.splice(2, 2);

console.log(arr); // Output: ['a', 'b', 'e']
console.log(removedElements); // Output: ['c', 'd']

// Adding elements to the arr starting from index 1 (inclusive) without removing any elements
arr.splice(1, 0, 'x', 'y');

console.log(arr); // Output: ['a', 'x', 'y', 'b', 'e']

 

6. slice(): 

It returns a shallow copy of portion of an array into a new array object selected from begin to end.

 

Syntax:

Array.slice(startIndex, endIndex);

 

Example:

let arr = ['a', 'b', 'c', 'd', 'e'];

// Extracting a portion of the arr from index 1 to index 3 (not inclusive)
let slicedArr = arr.slice(1, 3);

console.log(slicedArr); // Output: ['b', 'c']


// Extracting a portion of the arr from index 2 to the end
let slicedArr2 = arr.slice(2);

console.log(slicedArr2); // Output: ['c', 'd', 'e']

// Creating a shallow copy of the entire arr
let copiedArr = arr.slice();

console.log(copiedArr); // Output: ['a', 'b', 'c', 'd', 'e']

 

7. concat(): 

It returns a new array combining the array on which it is called.

 

Syntax:

Array.conscat(arr);

 

Example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = arr2.concat(arr1);

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