Approach 6 Using filter Method
The filter method in JavaScript creates a new array containing elements that pass a specified condition. It iterates through each element of the array, executing the condition for each element and including elements that return true in the filtered array.
Example: In this example we filters elements from the array that are greater than 2 using the filter method. The resulting filteredArray contains only these elements, and it is logged to the console.
const array = [1, 2, 3, 4, 5];
// Filter elements greater than 2
const filteredArray = array.filter(element => element > 2);
console.log(filteredArray);
Output
[ 3, 4, 5 ]
JavaScript Program to Access Elements in an Array
In this article, we will learn how to access elements in an array using JavaScript. The Arrays in JavaScript are zero-indexed which means the first element is accessed using index 0 and the second element with index 1 and so on. Accessing elements in an array is a fundamental operation and is essential for various programming tasks.
Below are the following approaches through which we can access elements in an array using JavaScript:
Table of Content
- Using square bracket notation
- Using loop(for or forEach or for…of) Method
- Using map() Method
- Using find() Method
- Using Destructuring Assignment
- Using filter Method