JavaScript arrays are one of the most commonly used data structures in the language. Arrays are a powerful and flexible tool that can be used to store and manipulate data in a variety of ways. Here are the top 10 array methods in JavaScript along with examples of how they can be used:
1. push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Example:
const array1 = [1, 2, 3];
array1.push(4);
console.log(array1); // [1, 2, 3, 4]
2. pop()
The pop() method removes the last element from an array and returns that element.
Example:
const array1 = [1, 2, 3];
const lastElement = array1.pop();
console.log(lastElement); // 3
console.log(array1); // [1, 2]
3. shift()
The shift() method removes the first element from an array and returns that element.
Example:
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(firstElement); // 1
console.log(array1); // [2, 3]
4. unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Example:
const array1 = [1, 2, 3];
array1.unshift(4, 5);
console.log(array1); // [4, 5, 1, 2, 3]
5. slice()
The slice() method returns a shallow copy of a portion of an array into a new array object.
Example:
const array1 = [1, 2, 3, 4, 5];
const array2 = array1.slice(1, 3);
console.log(array2); // [2, 3]
6. splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
Example:
const array1 = [1, 2, 3, 4, 5];
array1.splice(2, 1, 6);
console.log(array1); // [1, 2, 6, 4, 5]
7. concat()
The concat() method is used to merge two or more arrays into a new array.
Example:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const newArray = array1.concat(array2);
console.log(newArray); // [1, 2, 3, 4, 5, 6]
8. filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Example:
const array1 = [1, 2, 3, 4, 5];
const filteredArray = array1.filter(num => num > 2);
console.log(filteredArray); // [3, 4, 5]
9. map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Example:
const array1 = [1, 2, 3];
const mappedArray = array1.map(num => num * 2);
console.log(mappedArray); // [2, 4, 6]
10. reduce()
The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value.
Example:
const array1 = [1, 2, 3, 4, 5];
const reducedValue = array1.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(reducedValue); // 15
These are the top 10 array methods in JavaScript. There are many other methods available that can help you manipulate arrays in different ways. Understanding these methods will help you write more efficient and concise code.
Top comments (0)