Organize duplicates into individual array that is ordered

Tags: ,



I have an array with numbers. I would like to put the numbers in order and create new array with duplicats in the same array(array in array). Can someone please help me step by step. I would really like to understand

let arr = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

// I want to create this [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]

const sortArray = arr.sort(function(a, b) {
        return a - b;
    });

Answer

You can extract unique values using Set, then sort them (because sorting an array of arrays is more complex), then use array.reduce to acquire all the items in the original array and push either the single value if unique, otherwise the array of values (not sure why you need that, but still..)

Further documentation reference:

Working code below:

let arr = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

// I want to create this [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]

console.log([...new Set(arr)].sort((a,b) => a - b).reduce((accumulator, next) => {
	const filtered = arr.filter(i => i === next);
  return accumulator.push(filtered.length === 1 ? filtered[0] : filtered), accumulator
}, []));


Source: stackoverflow