JavaScript数组排序结果不符及去重需求技术问询
Hey there! Let's tackle your problem step by step—you've got two main things to fix here: getting the numeric sort right, and removing those duplicate values.
1. Why the default sort() isn't working as expected
The default sort() method in JavaScript sorts elements as strings, not numbers. That's why you're seeing [1, 21, 30, 4]—it's comparing the string representations of the numbers, so "4" comes after "30" because "4" has a higher Unicode value than "3".
To fix numeric sorting, you need to pass a comparator function to sort():
array1.sort((a, b) => a - b);
This tells JavaScript to compare the values numerically: if a - b is negative, a comes before b (ascending order).
2. Removing duplicate values
There are a few clean ways to do this, but one of the simplest is using a Set—a JavaScript object that only stores unique values. You can convert your sorted array to a Set, then convert it back to an array.
Putting it all together
Here's the full code that does both sorting and deduplication:
var array1 = [1, 1, 30, 4, 21]; // First sort numerically array1.sort((a, b) => a - b); // Then remove duplicates using Set var uniqueSortedArray = [...new Set(array1)]; console.log(uniqueSortedArray); // Output: [1, 4, 21, 30]
Alternative: Deduplicate without Set (for older environments)
If you need to support environments that don't have Set, you can loop through the sorted array and only keep unique values:
var array1 = [1, 1, 30, 4, 21]; array1.sort((a, b) => a - b); var uniqueSortedArray = []; for (let i = 0; i < array1.length; i++) { if (array1[i] !== array1[i - 1]) { uniqueSortedArray.push(array1[i]); } } console.log(uniqueSortedArray); // Same output: [1, 4, 21, 30]
That should give you exactly the result you're looking for!
内容的提问来源于stack exchange,提问作者Mitesh

