Skip to content Skip to sidebar Skip to footer

Concise Way To Return A New Array Of N Elements Filled With Iterated Values From Another Array? Vanilla Javascript

I have a given array with an undetermined quantity of elements, the array can be numbers or strings, then I need to generate a new array of N elements made from the iterated elemen

Solution 1:

You can tweak your second idea a bit - calculate the number of times you need to repeat the initial array to come up with the required number of total items, then flatten it and .slice:

let array = [1,2,3];
let length = 13;
const fromLength = Math.ceil(length / array.length);
let result = Array.from( { length: fromLength }, () => array )
  .flat()
  .slice(0, length);

console.log(result);

Solution 2:

I'll go with @CertainPerformance's answer. But here's a different approach, just for thinking-out-of-the-box purposes

// A function for getting an index up to length's size functiongetIDX(idx, length){
return idx <= length ? idx : getIDX(idx-length, length); 
}


const newArrayLength = 13;
const sourceArray = [1,2,3];
const resultArray = [];
for(let i=0; i< newArrayLength; i++){
resultArray[i]=sourceArray[getIDX(i+1, sourceArray.length)-1];
}

EDIT 1: I was comparing the performance of this approach versus the others here described and it seems that if you wanted to create a very large new array (ex: newArrayLength= 10000) the getIDX() function takes a lot to finish because of the size of the call stack. So I've improved the getIDX() function by removing the recursion and now the complexity is O(1) check it out:

function getIDX(idx,length){if(length===1){return idx};
const magicNumber =length*(Math.ceil(idx/length)-1);
 return idx - magicNumber;
}

With the new getIDX() function this approach seems to be the most performant. You can take a look to the tests here: https://jsbench.me/v7k4sjrsuw/1

Solution 3:

You can use a generator function that will create a repeating sequence from an input. You can add a limit to the generated sequence and simply turn it into an array:

function* repeatingSequence(arr, limit) {
  for(let i = 0; i < limit; i++) {
    const index = i % arr.length;
    yield arr[index];
  }
}

const generator = repeatingSequence(["dog", "cat", "sheep"], 10);

const result = Array.from(generator);

console.log(result);

Alternatively, you can make an infinite repeating sequence with no limit and then generate as many elements as you want for an array:

function* repeatingSequence(arr) {
  let i = 0while(true) {
    const index = i % arr.length;
    yield arr[index];
    i++;
  }
}

const generator = repeatingSequence(["dog", "cat", "sheep"]);

const result = Array.from({length: 10}, () => generator.next().value);

console.log(result);

Solution 4:

You can use modulo operator. Special thanks to @Vlaz for shorten version:

Array.from({ length:length }, (e, i) => array[ i  % array.length ])

An example:

let array = [1,2,3];
let length = 13;
const result = Array.from({ length:length }, 
    (e, i) => array[ i  % array.length ]);
console.log(result);

Post a Comment for "Concise Way To Return A New Array Of N Elements Filled With Iterated Values From Another Array? Vanilla Javascript"