I have an array of items that occur exactly twice, right next to eachother, like so:
const arr = ['1', '1', '2', '2', '3', '3']
I need to sort it in a different order, so all unique values occur first, and then their duplicates, like so:
const arr = ['1', '2', '3', '1', '2', '3']
How can I solve it by using sort()
function? Or is there another way I can achieve this?
I tried something like this, but it didn’t work:
const sorted = myDublicatedArray.sort((left, right) => left.index - right.index);
14
I can’t think of a way to do this only using Array.sort()
. The approach below should work for both numeric and string inputs unless there are other requirements:
const arrayWithDuplicates = ['1', '1', '2', '2', '3', '3'];
// convert to a Set to get unique values
const uniqueValues = new Set(arrayWithDuplicates);
// sort by value
const sortedArray = Array.from(uniqueValues).sort((a, b) => a - b);
// duplicate the sorted array
const arrayOrganized = [...sortedArray].concat(sortedArray);
console.log(arrayOrganized)
1
You could maintain an index for every value and get a grouped array as first and then a flat array as result.
const
array = ['1', '1', '2', '2', '3', '3'],
result = array
.reduce((indices => (r, v) => {
indices[v] ??= 0;
(r[indices[v]++] ??= []).push(v);
return r;
})({}), [])
.flat();
console.log(result);
1
From comments I understand that you will have pairs of duplicate values following one after the other, never 3 or more of the same. In that case, you can map the input array like this:
const arrayWithDuplicates = ['1', '1', '2', '2', '3', '3'];
const result = arrayWithDuplicates.map((_, i, a) => a[i * 2 % a.length]);
console.log(result);