I am pretty new to javascript, and I was trying to build this function I found in a challenge. I have managed to solve this, but I feel like this is a very complicated way of doing things, what would be the fastest method here?
Basically answer(array) should transform this:
const array = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
into this:
newArray = [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591];
Here is my code so far:
const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];
const duplicates = arr =>
arr.reduce((a, b) => ({ ...a,
[b]: (a[b] || 0) + 1
}), {})
array.sort((a, b) => a - b);
let array1 = duplicates(array);
var values = Object.values(array1);
var keys = Object.keys(array1);
var newArray = [];
for (let i = 0; i < keys.length; i++) {
let tempArray = [];
for (let j = 0; j < values[i]; j++) {
tempArray.push(keys[i]);
}
newArray.push(tempArray);
}
console.log(newArray);
duplicates function comes from This post about finding duplicate values