Skip to content
Advertisement

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

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement