How to Extract an Element from an Array in JavaScript?

Estimated read time 1 min read

You can extract an element from an array in JavaScript using the splice() method. The splice() method allows you to remove one or more elements from an array and optionally add new elements in their place. Here’s an example code snippet to extract an element from an array:

const array = ["apple", "banana", "cherry", "date"];

const extractedElement = array.splice(2, 1); // remove the element at index 2 (cherry)
console.log(extractedElement); // output: ["cherry"]

console.log(array); // output: ["apple", "banana", "date"]

In the above code, the splice() method is used to remove the element at index 2 (the third element) from the array. The splice() method returns an array containing the removed element(s), in this case, the single element “cherry”. The modified array now contains the remaining elements “apple”, “banana”, and “date”. Note that the original array is modified by the splice() method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply