Search code examples
javascriptarrayslimit

repeat array going up and down in with some limit


I have data in this form [1,2,3,4]. I want to perform some operation on this array so that I will get output like this [1,2,3,4, 4,3,2,1, 1,2]. Please, can you suggest some way for me to achieve this output?

// function declaration 

function arrayExm(array,limit){ 
  // want some operations here so that i will get this output
}

//function execution 

arrayExm([1,2,3,4],10) 
//so it will return [1,2,3,4, 4,3,2,1, 1,2]

Solution

  • You can achieve it using a simple for loop.

    function arrayExm(array, limit) {
      var res = [],
        len = array.length;
    
      // iterate upto the limit
      for (var i = 0; i < limit; i++) {
        // define the value based on the iteration 
        res[i] = Math.floor(i / len) % 2 == 0 ? // check the array element repetition is odd or even
          array[i % len] : // if even define element in same order   
          array[len - i % len - 1]; // if odd define element in reverse order
      }
    
      return res;
    };
    
    
    
    console.log(arrayExm([1, 2, 3, 4], 10))