-2
  1. Print every N-th Element from an Array Write a JS function that collects every element of an array, on a given step. The input comes as array of strings. The last element is N - the step. The collections are every element on the N-th step starting from the first one. If the step is "3", you need to print the 1-st, the 4-th, the 7-th … and so on, until you reach the end of the array. Then, print elements in a row, separated by single space.

Example: Input Output ['5', '20', '31', '4', '20', '2'] 5 31 20

  • 3
    Hi, welcome to Stack Overflow. Before asking others to help with your homework, please make a good faith attempt to solve the problem yourself first. Please read: [How do I ask and answer homework questions?](https://meta.stackoverflow.com/a/334823/3082296) and [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Feb 12 '19 at 13:18
  • how can you print every element one by one ? – ashish singh Feb 12 '19 at 13:18
  • 2
    Possible duplicate of [Javascript: take every nth Element of Array](https://stackoverflow.com/questions/33482812/javascript-take-every-nth-element-of-array) and [How to take every 3rd element of an array](https://stackoverflow.com/questions/41312888/) – adiga Feb 12 '19 at 13:19

1 Answers1

0

If you want to get the N-th positions and the only print it in the same array separated with spaces you can do it with this function

function splitByStep(step, arr)
{
    var steppedString = "";

    for(i = 0 ; i < arr.Lenght; i += step)
        steppedString += arr[i] + " ";

    console.log(steppedString);
}

step would be the '3' in your question and arr the array.

You need to use a for to go around array items, arrays are like boxes. To reach the positions they ask, you need to read only the N-th positions. The step is the space between positions. You only need to sum to first position (0) the step while the array is not toally chececk.

Mr.Deer
  • 476
  • 6
  • 17