How to get every Nth element of array in JavaScript

1 Answer

0 votes
function getEveryNthElement(arr, nth) {
  const result = [];

  for (let i = nth; i < arr.length; i += nth) {
    	result.push(arr[i]);
  }

  return result;
}

const arr =  [4, 5, 6, 7, 1, 9, 0, 3, 12, 97, 11];
const N = 3;

console.log(getEveryNthElement(arr, N));


  
  
  
  
/*
run:
  
[7, 0, 97]
  
*/

 



answered May 18, 2022 by avibootz
edited May 18, 2022 by avibootz
...