How to get every Nth element of array in TypeScript

1 Answer

0 votes
function getEveryNthElement(arr : Array<number>, nth : number) : Array<number>  {
    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, 98, 13, 2, 19];
const N = 3;

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


  
  
  
  
/*
run:
  
[7, 0, 98, 19]
  
*/

 



answered May 18, 2022 by avibootz
...