Retrieve the nth element from an array using a function that requires 2 arguments

During my coding journey, I encountered a challenge that has proven to be quite tricky. The task in question goes as follows:

  • Create a function that accepts an array (a) and a value (n) as parameters
  • Identify and store every nth element from the array in a new array
  • Return the newly created array

Here is the expected output:

console.log(myFunction([1,2,3,4,5,6,7,8,9,10],3))    //Expected [3,6,9]
console.log(myFunction([10,9,8,7,6,5,4,3,2,1],5))    //Expected [6,1]
console.log(myFunction([7,2,1,6,3,4,5,8,9,10],2))    //Expected [2,6,4,8,10]

I attempted to solve this puzzle but unfortunately missed the mark. Here's what I came up with:

function nthElementFinder(a, n) {
  return a.filter((e, i, a) => {
    const test = i % n === 0;
    return test;
  });
}
console.log(nthElementFinder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

Answer №1

Just a little tweak needed to get this function working perfectly. Remember, arrays in Javascript start at index 0, not 1. So make sure to adjust the index by adding 1 on each iteration:

function findNthElement(arr, n) {
  return arr.filter((elem, index, array) => {
    const test = (index + 1) % n === 0 ;
    return test;
  });
}
console.log(findNthElement([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

Answer №2

Another method to extract specific elements is by iterating through the array and selecting every nth item to add to a new array. This approach efficiently targets only the desired items without looping through all elements.

function findNthElements(arr, n) {
    const output = [];
    let index = n - 1;
    while (index < arr.length) {
        output.push(arr[index]);
        index += n;
    }
    return output;
}

console.log(findNthElements([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

Answer №3

Greetings @Bhaskar Deb, as you iterate through the array, selecting the nth element becomes almost effortless. The key part that matters is the remainder within the loop.

function doSomething(array, num) {


      let arr   = array,
          i     = array.length - 1,
          nth   = num;


      do {

          if(i % nth === 0) {
//           perform action for nth object here
          }

//           perform general actions on array here

        i--;

      } while (i > -1);


}

doSomething(yourArray, n);

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

Ancient queries carry the weight of time

Extremely ancient, very old, incredibly aged beyond belief ...

What techniques should be utilized for passing nested objects within an object array in React?

Within my map function below, I am attempting to access the nested objects in my data. I want to implement a functionality that states "If an object in my SlideData has the property 'list', then display it". When passing props from the data to my ...

Is it possible to receive an Infinite value from the Vector.project() function in Three.js

Could someone please explain why I am getting {x:Infinity, y:-Infinity, z:-Infinity} as my position values {x:0.50516157, y:-0.62950189, z:0} when attempting to project my position vector onto the camera? I have come across a similar issue on Stack Overf ...

Error: The Vue Class-Based module failed to parse due to an unexpected character '@'

When I run the command nmp run serve on my Vue project, I encounter two errors. I am following a tutorial that uses class-based Vue, but I am facing this error with all my imported Vue files. As a newcomer to Vue, I am puzzled as to why this error is occur ...

Understanding the Behavior of Vue 3's setInterval Methods

Environment I am working on a Vue 3 Application where I need to run a constant setInterval() in the background (Game Loop). To achieve this, I have placed the code in store/index.js and invoked it from views/Playground.vue's mounted() lifecycle hook ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

Performing a map or foreach function on an array of objects limited to the first 5 objects

I need to iterate through an array of objects, but I only want to loop through the first 5 objects and then stop. What is the most efficient way to achieve this? [ {"visibility": 10000,}, {"visibility": 10000,}, {"visibilit ...

Combining an array of intricate data models to create

Currently, my setup involves using Entity Framework 7 in conjunction with ASP.NET MVC 5. In my application, I have various forms that resemble the design showcased in this image. By clicking on the "new" button within these forms, a Bootstrap modal like t ...

In Flow, how is the asterisk (*) type utilized and what is its counterpart in TypeScript?

My expertise lies mostly in TypeScript, but I recently came across Flow which seems quite similar to TS in many aspects. However, one thing that caught my attention is the asterisk (*) type in Flow. Initially, I thought it was just another way of represent ...

Tips for integrating highcharts plugins with highcharts-vue (highcharts vue wrapper)

Currently, I am utilizing the Vue wrapper for Highcharts called highcharts-vue(https://github.com/highcharts/highcharts-vue). However, I am facing an issue where I need to detect the event of a right mouse click (contextmenu) on the chart. To address this, ...

"The Vue component's data is successfully updating within a method using setInterval(), however, the changes are not reflected in the DOM

I have a function in my methods that gets triggered with a @click in the view. The function starts a timer, and although it seems to work fine in the DevTools, the timer only updates in the DevTools when I refresh the page. Moreover, in the view, the time ...

What is the most effective method for exchanging variables between programs or threads?

I currently have a program that executes an algorithm processing real-time data. Once per hour, the algorithm's parameters are optimized based on new historical data. Currently, this optimization process is running in a single thread, pausing the rea ...

Unexpected behavior in ReactJS when using Material UI

In my Webpack + ReactJS project, I am working on creating a table using Material UI. I am trying to implement an 'icon menu' feature with a 'menu item' that allows users to delete a specific line along with its associated data. Below i ...

What are the steps to installing a .deb file offline using Docker?

I am planning to install a .deb file on my Docker container. In my Dockerfile, I execute the following command: RUN apt-get install -y ./fonts/ttf-mscorefonts-installer_3.6_all.deb ROOT Folder |->Dockerfile |->fonts |-> ttf ...

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...

Using HTML5 canvas to draw circles with additional metadata stored in variables

I'm designing a seating chart that will indicate spots with circles and show a tooltip on mouseover with the person's first name, last name, and possibly other details. I plan to use Kinetic.JS for region/tooltip support based on the tutorials I& ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

Mastering Protractor: Opening multiple sites and sending keys

My current task involves creating a script with a list of websites and corresponding amounts in a JSON format: { "URL": [{ "https://testing.com/en/p/-12332423/": "999" }, { "https://testing.com/en/p/-123456/": "123" ...

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...