I have an array, for example:
var arr = [2,4,7,11,25,608,65,109,99,100,504,606,607];
I need to make it so each value that is within range of its multiple of ten below and and multiple of ten above it is grouped together.
For example, 2,4,7 are between 0 and 10 so they must be together. 11 would be alone in its group, like 25,65 etc. 606,607,608 would be together.
The array above should become:
[ [2,4,7],[11],[25],[65],[99],[101],[504],[100,109],[606,607,608] ]
I've been thinking about it for a couple of hours and I wasn't able to come up with anything yet. It's really bad not much worth mentioning but so far I'm playing with Math.round (http://jsfiddle.net/40napnyx/2/)
Edit: I'd like to add another issue (although I will not pick the correct answer based on this if the actual answers don't include the solution of this new problem).
The array may contain values with letters. Those values should all be in the same group, in alphabetical order (only the first letter is taken to determine the order). This group should be the last value in the resulting array.
So for instance
var arr = [2, 4, 11,'a3', 25, 7, 'j', 'bzy4];
Would be [[2,4,7],[11],[25],['a3','bzy4', 'j']]
Here's a generic function:
function groupBy(ary, keyFunc) {
var r = {};
ary.forEach(function(x) {
var y = keyFunc(x);
r[y] = (r[y] || []).concat(x);
});
return Object.keys(r).map(function(y) {
return r[y];
});
}
// usage:
var arr = [2,4,7,11,25,608,65,99,101,504,606,607];
g = groupBy(arr, function(x) { return Math.floor(x / 10) });
document.write(JSON.stringify(g));
For your bonus question, just apply groupBy
twice:
function groupBy(ary, keyFunc) {
var r = {};
ary.forEach(function(x) {
var y = keyFunc(x);
r[y] = (r[y] || []).concat(x);
});
return Object.keys(r).map(function(y) {
return r[y];
});
}
var arr = [2, 4, 11,'a3', 25, 7, 'j', 'bzy4'];
g = groupBy(arr, isNaN);
g = [].concat(
groupBy(g[0], function(x) { return Math.floor(x / 10) }),
[g[1].sort()]
);
document.write(JSON.stringify(g));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With