我需要使用这个数组 [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20] 并返回一个新数组,它将所有重复的数字排序到它们自己的嵌套数组中.
它应该返回 [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]。
我已经弄乱了 for 循环以及 .map() 方法,但似乎无法找到解决方案。在这一点上,我几乎只是在黑暗中拍摄,希望能有所作为。我是 javascript 的新手。
const cleaner = array1.map((num, index, array) => {
if (array1.indexOf(num) >= index) {
return num;
} else {
return array;
}
});
最佳答案
您可以使用 Set
收集唯一值然后使用 Array.prototype.map()
和 Array.prototype.filter()
为每个值创建子数组。
const array = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
// defines a function that...
const arrange = array =>
// creates array of unique values
Array.from(new Set(array))
// sorts unique values in ascending order
.sort((a, b) => a - b)
// creates a subarray for each unique value
.map(key => array.filter(value => key === value))
// unwraps unit length subarrays
.map(subarray => subarray.length === 1 ? subarray[0] : subarray);
const cleaner = arrange(array);
console.log(JSON.stringify(cleaner));
这不是最有效的方法,但它比使用 reduce()
方法的过程方法更具可读性(在我看来),对于这种长度的数组,区别在于执行时间可以忽略不计。
关于javascript - 我有一组数字。我需要返回一个新数组,其中重复的数字位于它们自己的嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57420320/