Sichanov

14. Print Every N-th Element from an Array

Feb 25th, 2023
799
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr, num) {
  2.     let result = [];
  3.     if (num < arr.length) {
  4.         for (let i = 0; i < arr.length; i += num) {
  5.             result.push(arr[i]);
  6.         }
  7.     } else {
  8.         result = [arr[0],];
  9.     }
  10.     return result;
  11. }
  12.  
  13. solve(['5', '20', '31', '4', '20'], 2);
  14. solve(['1', '2', '3', '4', '5'], 6);
Advertisement
Add Comment
Please, Sign In to add comment