javascript grab only even array index

Javascript: Grabbing only Even Array Index

When it comes to working with arrays in Javascript, it's important to know how to manipulate the data in the array. One common task is to only grab the even array index. In this PAA, we'll discuss the different ways to achieve this.

Method 1: Using a for loop

The first method is using a for loop to loop through the array and only grab the even index values. Here's an example of how to do it:


const array = [1, 2, 3, 4, 5, 6];
const evenIndexArray = [];

for (let i = 0; i < array.length; i += 2) {
    evenIndexArray.push(array[i]);
}

console.log(evenIndexArray); // [1, 3, 5]

In this code, we first define our array with values ranging from 1 to 6. We then create a new empty array called evenIndexArray. We then use a for loop to loop through the original array and only grab the even index values by using i += 2 in our for loop declaration. We then push each even index value into our new array. Finally, we log the new array to the console.

Method 2: Using the filter method

The second method is using the filter() method to filter out the even index values. Here's an example of how to do it:


const array = [1, 2, 3, 4, 5, 6];
const evenIndexArray = array.filter((value, index) => {
    return index % 2 === 0;
});

console.log(evenIndexArray); // [1, 3, 5]

In this code, we first define our array with values ranging from 1 to 6. We then use the filter() method on the array to only keep the values where the index is even by checking if index % 2 === 0. We then assign the new filtered array to a variable called evenIndexArray. Finally, we log the new array to the console.

Method 3: Using the reduce method

The third method is using the reduce() method to only keep the even index values. Here's an example of how to do it:


const array = [1, 2, 3, 4, 5, 6];
const evenIndexArray = array.reduce((accumulator, currentValue, index) => {
    if (index % 2 === 0) {
        accumulator.push(currentValue);
    }
    return accumulator;
}, []);

console.log(evenIndexArray); // [1, 3, 5]

In this code, we first define our array with values ranging from 1 to 6. We then use the reduce() method on the array to only keep the values where the index is even by checking if index % 2 === 0. We then assign the new filtered array to a variable called evenIndexArray. Finally, we log the new array to the console.

These are three methods you can use to grab only even index values in a Javascript array. Choose the one that fits your scenario best and happy coding!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe