Array Methods:
push() => add one or more elements to the end of an array.
Example :
let fruits = ["Apple", "Banana"];
// Adding new elements using push()
fruits.push("Mango");
fruits.push("Orange", "Pineapple");
console.log(fruits);
// Output: ["Apple", "Banana", "Mango", "Orange", "Pineapple"]
pop() => remove the last element from an array.
Example :
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop(); // Removes "Mango"
console.log(fruits);
// Output: ["Apple", "Banana"]
shift() => remove the first element from an array.
Example :
let fruits = ["Apple", "Banana", "Mango"];
fruits.shift(); // Removes "Apple"
console.log(fruits);
// Output: ["Banana", "Mango"]
unshift() => add one or more elements to the beginning of an array.
Example :
let fruits = ["Banana", "Mango"];
fruits.unshift("Apple");
console.log(fruits);
// Output: ["Apple", "Banana", "Mango"]
splice() => add, remove, or replace elements in an array at a specific index.
Example :
let fruits = ["Apple", "Banana", "Mango", "Orange"];
fruits.splice(1, 2, "Grapes", "Pineapple");
// from index 1, remove 2 items, add Grapes, Pineapple
console.log(fruits);
// Output: ["Apple", "Grapes", "Pineapple", "Orange"]
slice() => create a shallow copy of a portion of an array.(It does not modify the original arrays)
Example :
let fruits = ["Apple", "Banana", "Mango", "Orange"];
let sliced = fruits.slice(1, 3); // from index 1 to 2
console.log(sliced);
// Output: ["Banana", "Mango"]
console.log(fruits);
// Original array not changed
concat() => merge two or more arrays into a new array.(It does not modify the original arrays)
Example :
let arr1 = ["Apple", "Banana"];
let arr2 = ["Mango", "Orange"];
let combined = arr1.concat(arr2);
console.log(combined);
// Output: ["Apple", "Banana", "Mango", "Orange"]
includes() => check if an array or string contains a specific value.
Example :
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana")); // true
console.log(fruits.includes("Orange")); // false
index() => find the index of the first occurrence of a specified value in a string or array.
Example :
let fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.indexOf("Orange")); // -1 (not found)
reverse() => reverse the order of elements in an array.
Example :
let fruits = ["Apple", "Banana", "Mango"];
fruits.reverse();
console.log(fruits);
// Output: ["Mango", "Banana", "Apple"]
sort() => sort the elements of an array.
Example :
let fruits = ["Mango", "Apple", "Banana"];
fruits.sort();
console.log(fruits);
// Output: ["Apple", "Banana", "Mango"]
let numbers = [40, 100, 1, 5];
numbers.sort((a, b) => a - b); // ascending sort
console.log(numbers);
// Output: [1, 5, 40, 100]
Top comments (0)