I have an array of tuples of coordinates like
[ [ 1, 1 ],
[ 2, 2 ],
[ 3, 3 ],
[ 4, 4 ],
[ 5, 5 ],
[ 6, 6 ],
[ 7, 7 ],
[ 8, 8 ],
[ 9, 9 ],
[ 10, 10 ]
...
I want to extract every 5th coordinates out of them into a new array
Here is my implementation
const coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1])
const { filteredCoordinates } = coordinates.reduce(
(accu, currCoordinate) => {
if (accu.count === 5) {
accu.filteredCoordinates.push(currCoordinate)
accu.count = 1
} else {
accu.count += 1
}
return accu
},
{
count: 1,
filteredCoordinates: [],
}
)
console.log(filteredCoordinates);
This works fine but I am wondering if there is a better way to do this?
You could take an index and increment it by the wanted count.
This approach does not iterate the complete array, only the wanted indices.
const
coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1]),
filtered = [];
for (let i = 4; i < coordinates.length; i += 5) filtered.push(coordinates[i]);
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can filter the array based on the modulo of five given the index.
const coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1])
const everyFithCoordinate = coordinates.filter((_, i) => (i+1) % 5 === 0);
console.log(everyFithCoordinate);
I want to extract every 5th coordinates out of them into a new array
Depending on your definition of "extract" you may be wanting to move those coordinates from the first to the second array. This example uses a for statement. I cache the length, and then splice out the coordinate from the array at the given index, and push it into the new array. Then decrement both the length and the index because they have changed before the next iteration.
const coordinates = Array.from({ length: 32 }, (_, i) => [i + 1, i + 1]);
const out = [];
const count = 5;
let { length } = coordinates;
for (let i = count - 1; i < length; i += count) {
out.push(coordinates.splice(i, 1)[0]);
--length;
--i;
}
console.log(JSON.stringify(out));
console.log(JSON.stringify(coordinates));