Issue: Count adjacent equal values in an array, so that the number of values in distinct groups can be used at a later time. Example:
[0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]
// should return
[3, 1, 1]
This array has 3 groups of 0's. A group of three and 2 groups of one. The goal was to return an array of these values as such: [3, 1, 1]. I can then compute averages, etc...for these groups.
I struggled with this for a few hours before using a brutish method.
function getGroups(arr) { };
Originally I tried to handle this with a loop that computed the sums during iteration and then spat these into their own arrays. This kept failing because the sums were 1 short, or returning NaN. I settled on chopping these up into sub-arrays to make things more manageable.
I define my storage for the subArrays, as well as something to track what array within my storage I will need to put my values to sum:
let zeroStorage = [];
let zeroCount = 0;
The intention behind having a count, is so that I can keep track of the current index within the storage and only put digits into that index should they meet my requirements. If it doesn't exist, I create a new array for that new instance of my integer.
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 0) {
zeroStorage[zeroCount] === undefined
? zeroStorage[zeroCount] = [1]
: death[zeroCount] = [...zeroStorage[zeroCount], 1];
} else zeroCount += 1;
}
Because I am adding one to the zeroStorage
array every time an index does not equal zero empty array slots are created. I am eliminating these with a filter, rather than trying to bend the logic to stop creating them as it was a simpler solution. I then map/reduce the leftover arrays to get just the totals for each subarray.
zeroStorage.filter(n => true)
.map(subArr => {
return subArray.reduce((a, b) => a + b);
});
Et voila, our shiny array for of [3, 1, 1]
.
This may not be the most sophisticated code as it relies on repeat iteration, but hey I'll take it! I am implementing this to filter on arrays of 0's and 1's so am not explaining how to elaborate to loop over other values.
Thanks for reading! Find the full code here.