Answer the question
In order to leave comments, you need to log in
Algorithm for turning a single-level list into a two-level one?
There is an array containing elements of two types (although in the general case there may be more than two types, but for now you can score on this). Specific objects are unimportant, let them be numbers and letters for clarity. It is necessary to combine consecutive elements of the same type into subarrays. For example:
[1, 2, a, b] =>
[1, 2, 3, a, 4, 5, b, 9, n, m] =>
[1] =>
[a] =>
[] => []
Answer the question
In order to leave comments, you need to log in
var arr = [1, 2, 3, 'a', 4, 5, 'b', 9, 'n', 'm'];
arr = arr.reduceRight(function(prev, el, i) {
if (prev.length == 0 ||
(typeof(el) != typeof(prev[0][0]))) {
prev.unshift([el]);
} else {
prev[0].unshift(el);
}
return prev;
}, []);
console.log(JSON.stringify(arr));
Here is what I myself gave birth to and what can be called more or less decent:
function group (input) {
var last = function (arr) {
return arr[arr.length - 1];
}
var output = [];
input.forEach(function (el) {
if (output.length === 0 || typeof(el) !== typeof(last(output)[0])) {
output.push([]);
}
last(output).push(el);
});
return output;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question