将重复项组织成有序的单个数组

bpo*_*lar 2 javascript arrays

我有一个数字数组。我想按顺序排列数字,并在同一数组(数组中的数组)中创建重复的新数组。有人可以帮我一步一步。我真的很想了解

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;
    });
Run Code Online (Sandbox Code Playgroud)

bri*_*eje 6

您可以使用提取唯一值Set,然后对它们进行排序(因为对数组的数组进行排序比较复杂),然后使用array.reduce获取原始数组中的所有项目,并在唯一的情况下推送单个值,否则就推送值数组(不确定为什么您需要它,但仍然..)

更多文档参考:

下面的工作代码:

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
}, []));
Run Code Online (Sandbox Code Playgroud)