Array methods in JavaScript are built-in functions designed to manipulate and work with arrays. Arrays are used to store collections of values and are essential for tasks such as data storage, iteration, and transformation.
Adds one or more elements to the end of an array.
let fruits = ["apple", "banana"];
let result = fruits.push("orange"); // ["apple", "banana", "orange"]
console.log(result); // ["apple", "banana", "orange"]
Removes the last element from the end of an array.
let fruits = ["apple", "banana", "orange"];
let result = fruits.pop(); // ["apple", "banana"]
console.log(result); // ["apple", "banana"]
Adds one or more elements to the beginning of an array.
let fruits = ["apple", "banana"];
let result = fruits.unshift("orange"); // ["orange", "apple", "banana"]
console.log(result); // ["orange", "apple", "banana"]
Removes the first element from the beginning of an array.
let fruits = ["apple", "banana", "orange"];
let result = fruits.shift(); // ["banana", "orange"]
console.log(result); // ["banana", "orange"]
Combines two or more arrays and returns a new array.
let array1 = [1, 2];
let array2 = [3, 4];
let combinedArray = array1.concat(array2); // [1, 2, 3, 4]
console.log(combinedArray); // [1, 2, 3, 4]
Converts all elements of an array into a string, separated by a specified delimiter.
let fruits = ["apple", "banana", "orange"];
let joinedString = fruits.join(", "); // "apple, banana, orange"
console.log(joinedString); // "apple, banana, orange"
Extracts a portion of an array into a new array without modifying the original.
let numbers = [1, 2, 3, 4, 5];
let subArray = numbers.slice(1, 4); // [2, 3, 4]
console.log(subArray); // [2, 3, 4]
Adds or removes elements from an array at a specified index.
let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "grape"); // ["apple", "grape", "orange"]
console.log(fruits); // ["apple", "grape", "orange"]
Find the index of a specified element.
let numbers = [1, 2, 3, 4, 2];
console.log(numbers.indexOf(2)); // 1
console.log(numbers.lastIndexOf(2)); // 4
Sorts the elements of an array in place.
let fruits = ["banana", "apple", "orange"];
fruits.sort(); // ["apple", "banana", "orange"]
console.log(fruits); // ["apple", "banana", "orange"]
Array methods provide powerful tools for working with arrays in JavaScript. They enable you to perform various operations like adding, removing, searching, and transforming elements within arrays.