How to Select Every Nth Item in an Array

Selecting every nth item from an array

A foreach loop provides the fastest iteration over your large array based on comparison testing. I'd stick with something similar to what you have unless somebody wishes to solve the problem with loop unrolling.

This answer should run quicker.

$result = array();
$i = 0;
foreach($source as $value) {
if ($i++ % 205 == 0) {
$result[] = $value;
}
}

I don't have time to test, but you might be able to use a variation of @haim's solution if you first numerically index the array. It's worth trying to see if you can receive any gains over my previous solution:

$result = array();
$source = array_values($source);
$count = count($source);
for($i = 0; $i < $count; $i += 205) {
$result[] = $source[$i];
}

This would largely depend on how optimized the function array_values is. It could very well perform horribly.

Javascript: take every nth Element of Array

Maybe one solution :

avoid filter because you don't want to loop over 10 000 elements !
just access them directly with a for loop !

 var log = function(val){document.body.innerHTML+='<div></pre>'+val+'</pre></div>'} 
var oldArr = [0,1,2,3,4,5,6,7,8,9,10]var arr = [];
var maxVal = 5;
var delta = Math.floor( oldArr.length / maxVal );
// avoid filter because you don't want// to loop over 10000 elements !// just access them directly with a for loop !// |// Vfor (i = 0; i < oldArr.length; i=i+delta) { arr.push(oldArr[i]);}

log('delta : ' + delta + ' length = ' + oldArr.length) ;log(arr);

Get every nth element of array with a function of 2 arguments

Beside the filtering solution, you could iterate and push each nth item to a new array. This approach does not visit all items, but only the nth ones.

function nthElementFinder(a, n) {
const result = [];
let i = n - 1;
while (i < a.length) {
result.push(a[i]);
i += n;
}
return result;
}

console.log(nthElementFinder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

How do you select every nth item in an array?

You could also use step:

n = 2
a = ["cat", "dog", "mouse", "tiger"]
b = (n - 1).step(a.size - 1, n).map { |i| a[i] }

How to extract every n-th row using array formula

use:

=FILTER(A5:A; MOD(ROW(A5:A)+1; 3)=0)

Sample Image



Related Topics



Leave a reply



Submit