Home > Mobile >  Get every nth element of array with a function of 2 arguments
Get every nth element of array with a function of 2 arguments

Time:07-28

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

CodePudding user response:

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

CodePudding user response:

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

  • Related