Using array methods, retrieve every alternate element from the array

As part of my learning journey, I successfully extracted every second element from an array using a for loop:

  const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  function filterEverySecond(arr) {
    let everySecondEl = [];
    for (let i = 0; i < arr.length; i += 2) {
      everySecondEl.push(arr[i]);
    }
    return everySecondEl;
  }

  console.log({
    numbers,
    result: filterEverySecond(numbers)
  });

Now, I am looking to achieve the same outcome without using a for loop, but instead by utilizing array methods such as forEach, filter, map, or reduce. Would appreciate some recommendations on which method would be most suitable for this scenario.

Answer №1

It's a breeze with the power of filter

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const filtered = numbers.filter((_, i) => i % 2 === 0)

console.log(filtered)

Simply exclude the elements with an odd index

Answer №2

To filter out elements from an array based on the index being divisible by 2, you can use the `filter` method:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log({
  numbers,
  result: numbers.filter((_, index) => index % 2 === 0)
});

Answer №3

If you want to filter based on index, use the filter method.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log({
    numbers,
    filteredNumbers: numbers.filter((num, index) => index % 2 === 0)
});

Answer №4

To achieve the desired result, you can utilize a for each loop in the following manner:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = [];

numbers.forEach(number => {
    if (number % 2 != 0) {
        result.push(number);
    }
});

console.log(numbers);
console.log(result);

The modulus operator calculates the remainder of division between two numbers. For instance: 1 % 2 will give a result of 1 as the remainder. Therefore, in the if statement, we are verifying if the number is not divisible by 2.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using curl to gather information and transferring it to a database via a submission form

After extensive research, I have successfully managed to collect data through curl and send it to a form that submits the information to my database. Utilizing guidance from this particular blog along with an existing product, the following code was implem ...

The compass is currently not displaying the magnetometer values

Hello! I am currently working on a code that displays the values of the magnetometer's (x, y, z) components. Unfortunately, the issue I am facing is that the code keeps returning a "null" value continuously. You can find the link to my expo snack here ...

What is the correct way to reference items during a loop iteration?

Take a look at http://jsfiddle.net/tAfkU/ When looping through an array, how can one correctly refer to the element of the array when callbacks are bound within the loop? var items = ["a", "b", "c"]; for(var i in items) { var this_item = items[i]; ...

What is the reason why calling setState does not update the local state?

Hello everyone, I came across an intriguing React task and I'm struggling a bit with finding the solution. Task: Can you figure out why this code isn't working and fix it? Code: class BugFixer extends React.Component { constructor(props) { ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

Component missing dark mode feature

I recently started using the Dropdown component from NextUI and managed to set up the dark mode based on the Dark mode documentation. However, when I implemented the Dropdown, it appeared in the light theme instead of the dark mode that I had configured: ...

Performing a Jquery Ajax get request on multiple URLs within a single function

In my current setup, I have a form with a select dropdown and three submit buttons labeled as "Daily new likes", "Daily unlikes" and "Daily page views". The form includes an Ajax call within the submitForm function that sends the selected option value to a ...

Unable to focus on input within a hidden div due to technical limitations

Can the focus() function be used on an input field that is located inside a hidden div with the following CSS properties: opacity: 0; visibility: hidden; When a button is clicked, the hidden div becomes visible by adding a new class to the body: Check ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

Form calculation

An issue has arisen with my calculating form for a client where an incorrect amount is displayed when 0.93 is entered into the percentage box. Original calculation: 10 x 10 x 15 x 0.93 = 13.95 Corrected calculation: 10 x 10 x 15 x 0.93 = 1.395 I am seek ...

The information window is malfunctioning on Google Maps

I created buttons that are linked to specific locations on a map and they seem to be functioning, although not in the most efficient way. However, when attempting to add an info window to appear on the marker, it does not work as expected. I am unsure of ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

The integration of ASPNetSpell Spell Checker with CKEditor 3 is not functioning properly on Chrome browsers

In my efforts to incorporate ASPNetSpell's spell checker () into CKEditor (), I have encountered some unexpected behavior across different browsers - IE 8+, FireFox 12, and Chrome 18.0.1025.152m. The issue seems to be that in Chrome, ASPNetSpell is u ...

Refreshingly modernizing SVG in Angular

I've been facing a challenge in my Angular application where I am trying to dynamically add paths to an SVG element within an HTML file. The issue is that even though the paths are getting added to the DOM, they are not showing up in the browser when ...

Improving the implementation of in-memory caching in javascript/nodejs

One thing that comes to mind is the issue of memory leaks. Consider this code snippet: let inMemoryCache = {}; app.get("/hello",(req, resp) => { inMemoryCache[unixTimeStamp] = {"foo":"bar"} resp.json({}); }); It&apo ...

Chakra UI: Trouble with applying a personalized font from Fontsource

I recently added a new font from Fontsource called Girassol () by running the following command: npm install @fontsource/girassol In addition, I have a file named theme.ts with the following content: import { extendTheme } from "@chakra-ui/react" ...

The toggle button in the navbar takes its time to vanish completely

Every time I try to close my navbar, it seems to take forever for the navbar to disappear. Below is the code snippet: HTML <!-- logo --> <div class="logo"> <img src="assets/logo.png" alt="logo g's s ...

Cannot locate JSON file in NodeJS

Currently, I am developing an express API and looking to establish a connection with a MySQL server using this API. The configuration settings are stored in a file named settings.json. To retrieve these settings, I am utilizing the following code: const c ...

Verify whether the text field is filled or not excluding the placeholder

How can I detect if a div is empty except for the placeholder element/value? Scenario 1: Div is empty <div id="textarea" contenteditable="true"> <span id="textarea-placeholder" data-text="Enter comment" ...

NodeJs simple mock: Capturing query string parameters with ease

I'm currently developing a basic mock server using only JavaScript and Yarn. Simply put, I have this functional code snippet: function server() { (...) return { users: generate(userGenerator, 150) } This piece of code successfully generates 15 ...