'JS Sort an array into three occurrences [closed]
I need to arrange the array so that three are only instances left or less, for example
let tab = [ 3, 3, 4, 4, 5, 4, 5, 6, 6, 4, 6, 3, 7, 7, 3]
I would like to get something like this initially;
let newTab = [3,3,3,4,4,4,5,5,6,6,6,7,7]
I am asking for help because I have no idea anymore.
Solution 1:[1]
You could group the data by thie value and take only the max length of three items for each group.
As result take the values in a flat array.
const
tab = [3, 3, 4, 4, 5, 4, 5, 6, 6, 4, 6, 3, 7, 7, 3],
result = Object
.values(tab.reduce((r, v) => {
r[v] ??= [];
if (r[v].length < 3) r[v].push(v);
return r;
}, {}))
.flat();
console.log(...result);
Solution 2:[2]
You could reduce() to an intermediate count object, and then flatMap() arrays of the correct size:
const tab = [ 3, 3, 4, 4, 5, 4, 5, 6, 6, 4, 6, 3, 7, 7, 3];
const result = Object.entries(
tab.reduce((a, v) => ({...a, [v]: (a[v] || 0) + 1}), {})
).flatMap(([v, count]) => new Array(Math.min(count, 3)).fill(+v));
console.log(result);
Sorting is achieved by virtue of integer object keys being numerically sorted by default.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
| Solution 2 |
