简体   繁体   中英

Get every nth element of array with a function of 2 arguments

I've been working on some challenges and this is one of the challenges I've been unable to get a solution of. This task is like this:

  • Write a function that takes an array (a) and a value (n) as arguments
  • Save every nth element in a new array
  • Return the new array

This is the output I'm expecting:

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]

This is what I've tried to figure out, but that wasn't it:

 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));

You almost have it. An array in Javascript (and most other languages) are 0-based meaning the first position has index = 0. So your function just needs to add 1 to the index on each iteration:

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

Beside the filtering solution, you could iterate and push each nth item to a new array. This approach does not visit all items, but only the nth ones.

 function nthElementFinder(a, n) { const result = []; let i = n - 1; while (i < a.length) { result.push(a[i]); i += n; } return result; } console.log(nthElementFinder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

@Bhaskar Deb, since you're iterating through the array anyway, you get nth element selection (almost) for free. This doesn't run, because the only relevant bit is the remainder part inside the loop.

function whatever(a, n) {


      let arr   = a,
          i     = a.length - 1,
          nth   = n;


      do {

          if(i % nth === 0) {
//           do your nth object stuff here
          }

//           do your array stuff here

        i--;

      } while (i > -1);


}

whatever(yourArray, n);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM