Javascript Javascript数组排序和唯一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4833651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:19:03  来源:igfitidea点击:

Javascript array sort and unique

javascriptarrayssortingunique

提问by theHack

I have a JavaScript array like this:

我有一个这样的 JavaScript 数组:

var myData=['237','124','255','124','366','255'];

I need the array elements to be unique and sorted:

我需要数组元素是唯一的和排序的:

myData[0]='124';
myData[1]='237';
myData[2]='255';
myData[3]='366';

Even though the members of array look like integers, they're not integers, since I have already converted each to be string:

尽管数组的成员看起来像 integers,但它们不是 integers,因为我已经将每个成员转换为字符串:

var myData[0]=num.toString();
//...and so on.

Is there any way to do all of these tasks in JavaScript?

有没有办法在 JavaScript 中完成所有这些任务?

回答by lonesomeday

This is actually very simple. It is much easier to find unique values, if the values are sorted first:

这其实很简单。如果首先对值进行排序,则查找唯一值要容易得多:

function sort_unique(arr) {
  if (arr.length === 0) return arr;
  arr = arr.sort(function (a, b) { return a*1 - b*1; });
  var ret = [arr[0]];
  for (var i = 1; i < arr.length; i++) { //Start loop at 1: arr[0] can never be a duplicate
    if (arr[i-1] !== arr[i]) {
      ret.push(arr[i]);
    }
  }
  return ret;
}
console.log(sort_unique(['237','124','255','124','366','255']));
//["124", "237", "255", "366"]

回答by mrmonkington

This might be adequate in circumstances where you can't define the function in advance (like in a bookmarklet):

在您无法提前定义函数的情况下(例如在书签中),这可能就足够了:

myData.sort().filter(function(el,i,a){return i===a.indexOf(el)})

回答by meteorBuzz

You can now achieve the result in just oneline of code.

您现在可以达到的效果,在短短一个行代码。

Using new Setto reduce the array to unique set of values. Apply the sortmethod after to order the string values.

使用新的 Set将数组减少到唯一的一组值。在字符串值进行排序之后应用sort方法。

var myData=['237','124','255','124','366','255']

var uniqueAndSorted = [...new Set(myData)].sort() 

UPDATEDfor newer methods introduced in JavaScript since time of question.

更新自提问时间以来 JavaScript 中引入的较新方法。

回答by ioleo

function sort_unique(arr) {
    return arr.sort().filter(function(el,i,a) {
        return (i==a.indexOf(el));
    });
}

回答by phaux

Here's my (more modern) approach using Array.protoype.reduce():

这是我使用的(更现代的)方法Array.protoype.reduce()

[2, 1, 2, 3].reduce((a, x) => a.includes(x) ? a : [...a, x], []).sort()
// returns [1, 2, 3]


Edit:More performant version as pointed out in the comments:

编辑:如评论中所指出的,性能更高的版本:

arr.sort().filter((x, i, a) => !i || x != a[i-1])

回答by glampr

How about:

怎么样:

array.sort().filter(function(elem, index, arr) {
  return index == arr.length - 1 || arr[index + 1] != elem
})

This is similar to @loostro answer but instead of using indexOf which will reiterate the array for each element to verify that is the first found, it just checks that the next element is different than the current.

这类似于@loostro 答案,但不是使用 indexOf 将重复每个元素的数组以验证它是第一个找到的元素,它只是检查下一个元素是否与当前元素不同。

回答by Raynos

Try using an external library like underscore

尝试使用像下划线这样的外部库

var f = _.compose(_.uniq, function(array) {
    return _.sortBy(array, _.identity);
});

var sortedUnique = f(array);

This relies on _.compose, _.uniq, _.sortBy, _.identity

这依赖于_.compose, _.uniq, _.sortBy,_.identity

See live example

查看现场示例

What is it doing?

它在做什么?

We want a function that takes an array and then returns a sorted array with the non-unique entries removed. This function needs to do two things, sorting and making the array unique.

我们想要一个函数,它接受一个数组,然后返回一个已删除非唯一条目的排序数组。这个函数需要做两件事,排序和使数组唯一。

This is a good job for composition, so we compose the unique & sort function together. _.uniqcan just be applied on the array with one argument so it's just passed to _.compose

这是一个很好的组合工作,所以我们将 unique & sort 功能组合在一起。_.uniq可以只用一个参数应用于数组,所以它只是传递给_.compose

the _.sortBy function needs a sorting conditional functional. it expects a function that returns a value and the array will be sorted on that value. Since the value that we are ordering it by is the value in the array we can just pass the _.identity function.

_.sortBy 函数需要一个排序条件函数。它需要一个返回值的函数,并且数组将根据该值进行排序。由于我们对其进行排序的值是数组中的值,因此我们可以只传递 _.identity 函数。

We now have a composition of a function that (takes an array and returns a unique array) and a function that (takes an array and returns a sorted array, sorted by their values).

我们现在有一个函数(接受一个数组并返回一个唯一数组)和一个函数(接受一个数组并返回一个按其值排序的排序数组)的组合。

We simply apply the composition on the array and we have our uniquely sorted array.

我们简单地将组合应用于数组,我们就有了唯一排序的数组。

回答by Victor

This function doesn't fail for more than two duplicates values:

对于超过两个重复值,此函数不会失败:

function unique(arr) {
    var a = [];
    var l = arr.length;
    for(var i=0; i<l; i++) {
        for(var j=i+1; j<l; j++) {
            // If a[i] is found later in the array
            if (arr[i] === arr[j])
              j = ++i;
        }
        a.push(arr[i]);
    }
    return a;
};

回答by justin.m.chase

Here is a simple one liner with O(N), no complicated loops necessary.

这是一个简单的单衬O(N),不需要复杂的循环。

> Object.keys(['a', 'b', 'a'].reduce((l, r) => l[r] = l, {})).sort()
[ 'a', 'b' ]

Explanation

解释

Original data set, assume its coming in from an external function

原始数据集,假设它来自外部函数

const data = ['a', 'b', 'a']

We want to group all the values onto an object as keys as the method of deduplication. So we use reduce with an object as the default value:

我们希望将所有值组合到一个对象上作为重复数据删除方法的键。所以我们使用 reduce 和一个对象作为默认值:

[].reduce(fn, {})

The next step is to create a reduce function which will put the values in the array onto the object. The end result is an object with a unique set of keys.

下一步是创建一个reduce 函数,它将数组中的值放到对象上。最终结果是一个具有一组唯一键的对象。

const reduced = data.reduce((l, r) => l[r] = l, {})

We set l[r] = lbecause in javascript the value of the assignment expression is returned when an assignment statement is used as an expression. lis the accumulator object and ris the key value. You can also use Object.assign(l, { [r]: (l[r] || 0) + 1 })or something similar to get the count of each value if that was important to you.

我们设置l[r] = l是因为在 javascript 中,当赋值语句用作表达式时,会返回赋值表达式的值。l是累加器对象,r是键值。Object.assign(l, { [r]: (l[r] || 0) + 1 })如果这对您很重要,您还可以使用或类似的东西来获取每个值的计数。

Next we want to get the keys of that object

接下来我们要获取该对象的键

const keys = Object.keys(reduced)

Then simply use the built-in sort

然后只需使用内置排序

console.log(keys.sort())

Which is the set of unique values of the original array, sorted

哪个是原始数组的唯一值集合,排序

['a', 'b']

回答by Amiga500Kid

No redundant "return" array, no ECMA5 built-ins (I'm pretty sure!) and simple to read.

没有多余的“返回”数组,没有 ECMA5 内置函数(我很确定!)并且易于阅读。

function removeDuplicates(target_array) {
    target_array.sort();
    var i = 0;

    while(i < target_array.length) {
        if(target_array[i] === target_array[i+1]) {
            target_array.splice(i+1,1);
        }
        else {
            i += 1;
        }
    }
    return target_array;
}