我有一个恰好出现两次的项目数组,彼此相邻,如下所示:
const arr = ['1', '1', '2', '2', '3', '3']
我需要以不同的顺序对其进行排序,因此所有唯一值首先出现,然后是它们的重复项,如下所示:
const arr = ['1', '2', '3', '1', '2', '3']
如何使用
sort()
函数解决这个问题?或者还有其他方法可以实现这一目标吗?
我尝试过类似的方法,但没有成功:
const sorted = myDublicatedArray.sort((left, right) => left.index - right.index);
我想不出仅使用
Array.sort()
来做到这一点的方法。除非有其他要求,否则下面的方法应该适用于数字和字符串输入:
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)
您可以为每个值维护一个索引,并首先获得分组数组,然后获得平面数组作为结果。
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);
从评论中我了解到,您将有对一个接一个的重复值,而不是3个或更多相同的值。在这种情况下,您可以像这样映射输入数组:
const arrayWithDuplicates = ['1', '1', '2', '2', '3', '3'];
const result = arrayWithDuplicates.map((_, i, a) => a[i * 2 % a.length]);
console.log(result);