Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Fetch alternative even values from a JavaScript array?
To fetch alternative even values from a JavaScript array, you need to iterate through the array and check if the index is even using the modulo operator. An index is even when index % 2 == 0.
Syntax
if (index % 2 == 0) {
// This will select elements at even positions (0, 2, 4, ...)
}
Example
The following example demonstrates how to fetch alternative even values from an array:
var subjectsName = ["MySQL", "JavaScript", "MongoDB", "C", "C++", "Java"]; for (let index = 0; indexOutput
Subject name at even position = MySQL Subject name at even position = MongoDB Subject name at even position = C++Using filter() Method
You can also use the
filter()method with index parameter to achieve the same result:var subjectsName = ["MySQL", "JavaScript", "MongoDB", "C", "C++", "Java"]; var evenPositionElements = subjectsName.filter((element, index) => index % 2 == 0); console.log("Elements at even positions:"); evenPositionElements.forEach(element => console.log(element));Output
Elements at even positions: MySQL MongoDB C++How It Works
The modulo operator
%returns the remainder of division. Whenindex % 2equals 0, it means the index is divisible by 2, making it an even position. Array indices start from 0, so positions 0, 2, 4, etc. are considered even positions.Conclusion
Use
index % 2 == 0condition in loops or thefilter()method to extract elements at even positions. This technique is useful for processing every alternate element in an array.
