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