Can this code be Improved? It arrange our array into sorted list(sortedArray) first and, the finalArray takes the final result;Example finalArray = [[1,1,1,1][2,2,2]…]
let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
let sortedArray = []
let finalArray = []
sortedArray = array.sort((a, b) => {
if (a > b) return 1;
if (a < b) return -1;
return sortedArray.push(a - b);
});
finalArray = sortedArray.reduce((item, index) => {
if (typeof item.last === 'undefined' || item.last !== index) {
item.last = index;
item.sortedArray.push([]);
}
item.sortedArray[item.sortedArray.length - 1].push(index);
return item;
}, {
sortedArray: []
}).sortedArray;
console.log(finalArray);
>Solution :
Here is a shorter version than yours and more readable than Nina’s
let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
const finalArray = array.slice(0) // copy the array
.reduce((acc,cur) => {
const idx = acc.findIndex(item => item[0] === cur);
if (idx !=-1) acc[idx].push(cur); // just push
else acc.push([cur]); // push as array
return acc
},[])
.sort(([a],[b]) => a-b); // sort on the first entry
console.log(finalArray);