Adding arrays to an array of arrays
I took your code and changed some parts.
Array#sort
sorts in place. No need to assign to a new variable.Iterate from zero and have a look to the data directly, by using the value at index minus one and at the index. If unequal, a new group is found. In this case just assign an empty array to
groupArray
and push the group to the result.Instead of using the same object reference and just empty the array by assigning zero to
length
, this approach takes a new array.Push the value outside of the
if
statement, because it was doubled in then and else part.Finally return the array with the groups.
function cleanTheRoom(array) {
let result = [];
let groupArray;
array.sort(function(a, b) {
return a - b;
});
for (let i = 0; i < array.length; i++) {
if (array[i - 1] !== array[i]) {
groupArray = [];
result.push(groupArray);
}
groupArray.push(array[i]);
}
return result;
}
let randomArray = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];
console.log(cleanTheRoom(randomArray));