How to find nth element of Array using Javascript methods?

An array in JavaScript starts at 0th index. That means, the first item of an array is at 0th position. To find the nth element of an array in JavaScript, you will get the element at n-1 position in the array. For example, if you want the 3rd item of any array, you will get the item at index 2, i.e., 3-1.

The following example get the 3rd item from a JavaScript array. 

const numArray = {1, 3, 5, 7, 9}
cost item = numArray[2];

To find the nth element of an array in JavaScript, you can also use the Array.prototype.slice() method to get a subarray containing the element you want, and then access the first element of the subarray.

For example, consider the following array:

const arr = [1, 2, 3, 4, 5];

To get the third element of this array (which has an index of 2), you can use the following code:

const thirdElement = arr.slice(2, 3)[0];
console.log(thirdElement); // Output: 3

Alternatively, you can use the Array.prototype.find() method to get the element that meets a certain condition. For example, to get the third element of the array (which has a value of 3), you can use the following code:

const thirdElement = arr.find((elem, index) => index === 2);
console.log(thirdElement); // Output: 3

You can also use the Array.prototype.filter() method to get all elements that meet a certain condition, and then access the element you want by its index. For example, to get the third element of the array (which has a value of 3), you can use the following code:

const thirdElement = arr.filter((elem, index) => index === 2)[0];
console.log(thirdElement); // Output: 3

Note that all of these methods start counting elements from index 0, so to get the nth element of the array, you will need to use an index of n - 1.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.