You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组排序结果不符及去重需求技术问询

Fixing Your Array Sorting and Duplicate Removal Issue

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:24:32