How could the return of an Array be made more efficiently after a given interval?
Array:
[1,2,3,4,5,6,7,8,9]
Return:
[3,6,9]
How could the return of an Array be made more efficiently after a given interval?
Array:
[1,2,3,4,5,6,7,8,9]
Return:
[3,6,9]
You should use the Array.filter() function.
const interval = 3;
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const results = myArray.filter((item, i) => {
const index = i + 1;
if (index % interval === 0) {
return true;
}
return false;
});
console.info(results); // [3, 6, 9]
You can also write this really shorthand, as follows:
const results = myArray.filter((_, i) => ((i + 1) % interval === 0));
It's really easy to do, just define your interval and check if it is met or not.
I'd suggest trying to do it yourself before looking at my example. If you need help, then read this. Stat by looping through all your items in the array, and check if they are a multiple of three (I'm guessing that is what your example suggests). If they are, add them to a new array, and once the loop terminates, return the new array.
If you still can't figure it out, here's my example
let intArray = [1,2,3,4,5,6,7,8,9];
console.log(getIntervalsFromArray(intArray, 3));
function getIntervalsFromArray(array, interval) {
let outputArray = [];
array.forEach(function(item, index) {
// Modulo to see if item is in the interval
if ((index + 1) % interval === 0) {
outputArray.push(item);
}
});
// Return the new array
return outputArray;
}
const getInterval = (arr, interval) => arr.filter((_, i) => (i + 1) % interval === 0);
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(getInterval(arr, 2).join(','));
console.log(getInterval(arr, 3).join(','));
console.log(getInterval(arr, 4).join(','));
You can iterate in a for-loop
while incrementing the index
by the specified interval
at each iteration as follows:
let arr = [1,2,3,4,5,6,7,8,9];
console.log( "Interval 3: "+getIntervalList(arr, 3) );
console.log( "Interval 2: "+getIntervalList(arr, 2) );
console.log( "Interval 1: "+getIntervalList(arr, 1) );
console.log( "Interval 9: "+getIntervalList(arr, 9) );
console.log( "Interval 0: "+getIntervalList(arr, 0) );
console.log( "Interval 10: "+getIntervalList(arr, 10) );
function getIntervalList(arr, interval){
if(interval <= 0 || interval > arr.length)
return [];
let list = [];
for(let i = interval-1; i < arr.length; i+=interval)
list.push(arr[i]);
return list;
}
This should do the job. Checks if your quota is over the limit too.
function giveMeAnArrayPlease(var interval, var array){
var array_len = array.length;
let list = [];
var quotient = Math.floor(array_len/interval);
if(interval <= 0 || interval > array.len)
return [];
for(let i = 0; i < array_len; i+=interval){
if(i > quotient)
break;
list.push(arr[i]);
}
return list;
}
function customReturn(myarray,interval){
var return_array = [];
var i;
for (i = 0; i <= myarray.length; i++) {
if(i % interval == 0)
return_array.push(myarray[i])
}
return return_array;
}