如何从JavaScript中包含重复值的数组中获取唯一值数组?(复制)

时间:2023-01-01 12:42:35

This question already has an answer here:

这个问题已经有了答案:

Given a ['0','1','1','2','3','3','3'] array, the result should be ['0','1','2','3'].

给定一个[' 0 ',' 1 ',' 1 ',' 2 ',' 3 ',' 3 ',' 3 ']数组,结果应该[' 0 ',' 1 ',' 2 ',' 3 ']。

17 个解决方案

#1


247  

Edited

编辑

ES6 solution:

ES6解决方案:

[...new Set(a)];

Alternative:

选择:

Array.from(new Set(a));

Old response. O(n^2) (do not use it with large arrays!)

旧的回应。O(n ^ 2)(不要使用大数组!)

var arrayUnique = function(a) {
    return a.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
};

#2


47  

If you want to maintain order:

如果你想维持秩序:

arr = arr.reverse().filter(function (e, i, arr) {
    return arr.indexOf(e, i+1) === -1;
}).reverse();

Since there's no built-in reverse indexof, I reverse the array, filter out duplicates, then re-reverse it.

由于没有内置的反向索引,所以我反向数组,过滤重复的数组,然后再反向。

The filter function looks for any occurence of the element after the current index (before in the original array). If one is found, it throws out this element.

过滤器函数在当前索引(在原始数组中之前)查找元素的任何出现。如果找到一个,它会抛出这个元素。

Edit:

编辑:

Alternatively, you could use lastindexOf (if you don't care about order):

或者,您可以使用lastindexOf(如果您不关心顺序的话):

arr = arr.filter(function (e, i, arr) {
    return arr.lastIndexOf(e) === i;
});

This will keep unique elements, but only the last occurrence. This means that ['0', '1', '0'] becomes ['1', '0'], not ['0', '1'].

这将保留唯一的元素,但只保留最后的元素。这意味着[' 0 ',' 1 ',' 0 ']是[' 1 ',' 0 '),而不是(“0”,“1”)。

#3


26  

Here is an Array Prototype function:

这是一个数组原型函数:

Array.prototype.unique = function() {
    var unique = [];
    for (var i = 0; i < this.length; i++) {
        if (unique.indexOf(this[i]) == -1) {
            unique.push(this[i]);
        }
    }
    return unique;
};

#4


13  

With underscorejs

与underscorejs

_.uniq([1, 2, 1, 3, 1, 4]); //=> [1, 2, 3, 4]

#5


13  

It's 2014 now guys, and time complexity still matters!

现在是2014年了,时间的复杂性仍然很重要!

array.filter(function() {
  var seen = {};
  return function(element, index, array) {
    return !(element in seen) && (seen[element] = 1);
  };
}());

http://jsperf.com/array-filter-unique/13

http://jsperf.com/array-filter-unique/13

#6


9  

function array_unique(arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i]);
        }
    }
    return result;
}

Not a built in function. If the product list does not contain the item, add it to unique list and return unique list.

不是一个内置函数。如果产品列表不包含项目,将其添加到唯一列表并返回唯一列表。

#7


7  

There you go! You are welcome!

你走吧!你是受欢迎的!

Array.prototype.unique = function()
{
    var tmp = {}, out = [];
    for(var i = 0, n = this.length; i < n; ++i)
    {
        if(!tmp[this[i]]) { tmp[this[i]] = true; out.push(this[i]); }
    }
    return out;
}

var a = [1,2,2,7,4,1,'a',0,6,9,'a'];
var b = a.unique();
alert(a);
alert(b);

#8


3  

You can find all kinds of array unique implementations here:

你可以在这里找到所有类型的数组唯一实现:

http://jsperf.com/distinct-hash-vs-comparison/12

http://jsperf.com/distinct-hash-vs-comparison/12

http://jsperf.com/array-unique-functional

http://jsperf.com/array-unique-functional

I prefer functional styles such as:

我喜欢功能性的风格,比如:

var arr = ['lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg'];

var newarr = arr.reduce(function (prev, cur) {
    //console.log(prev, cur);
    if (prev.indexOf(cur) < 0) prev.push(cur);
    return prev;
}, []);

var secarr = arr.filter(function(element, index, array){
    //console.log(element, array.indexOf(element), index);
    return array.indexOf(element) >= index;
});

//reverses the order
var thirdarr = arr.filter(function (e, i, arr) {
    //console.log(e, arr.lastIndexOf(e), i);
    return arr.lastIndexOf(e) === i;
});

console.log(newarr);
console.log(secarr);
console.log(thirdarr);

#9


1  

function array_unique(nav_array) {
    nav_array = nav_array.sort(function (a, b) { return a*1 - b*1; });      
    var ret = [nav_array[0]];       
    // Start loop at 1 as element 0 can never be a duplicate
    for (var i = 1; i < nav_array.length; i++) { 
        if (nav_array[i-1] !== nav_array[i]) {              
            ret.push(nav_array[i]);             
        }       
    }
    return ret;     
}

#10


1  

This will work. Try it.

这将工作。试一试。

function getUnique(a) {
  var b = [a[0]], i, j, tmp;
  for (i = 1; i < a.length; i++) {
    tmp = 1;
    for (j = 0; j < b.length; j++) {
      if (a[i] == b[j]) {
        tmp = 0;
        break;
      }
    }
    if (tmp) {
      b.push(a[i]);
    }
  }
  return b;
}

#11


1  

I like to use this. There is nothing wrong with using the for loop, I just like using the build-in functions. You could even pass in a boolean argument for typecast or non typecast matching, which in that case you would use a for loop (the filter() method/function does typecast matching (===))

我喜欢用这个。使用for循环没有错,我只是喜欢使用内建函数。您甚至可以为类型转换或非类型转换传递一个布尔参数,在这种情况下,您将使用for循环(filter()方法/函数执行类型转换匹配(==)))

Array.prototype.unique =
function()
{
    return this.filter(
        function(val, i, arr)
        {
            return (i <= arr.indexOf(val));
        }
    );
}

#12


1  

No redundant "return" array, no ECMA5 (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;
}

#13


1  

Here is the way you can do remove duplicate values from the Array.

以下是从数组中删除重复值的方法。

function ArrNoDupe(dupArray) {
   var temp = {};
    for (var i = 0; i < dupArray.length; i++) {
         temp[dupArray[i]] = true;
         var uniqueArray = [];
       for (var k in temp)
           uniqueArray.push(k);
 return uniqueArray;
    }
}

#14


1  

Another approach is to use an object for initial storage of the array information. Then convert back. For example:

另一种方法是使用对象来初始存储数组信息。然后再转换回来。例如:

var arr = ['0','1','1','2','3','3','3'];
var obj = {};

for(var i in arr) 
    obj[i] = true;

arr = [];
for(var i in obj) 
    arr.push(i);

Variable "arr" now contains ["0", "1", "2", "3", "4", "5", "6"]

变量“加勒比海盗”现在包含(“0”、“1”、“2”、“3”、“4”、“5”、“6”)

#15


0  

Those of you who work with google closure library, have at their disposal goog.array.removeDuplicates, which is the same as unique. It changes the array itself, though.

使用谷歌闭包库的人可以使用google .array。removeduplicate,与unique相同。不过,它改变了数组本身。

#16


-1  

    //
    Array.prototype.unique =
    ( function ( _where ) {
      return function () {
        for (
          var
          i1 = 0,
          dups;
          i1 < this.length;
          i1++
        ) {
          if ( ( dups = _where( this, this[i1] ) ).length > 1 ) {
            for (
              var
              i2 = dups.length;
              --i2;
              this.splice( dups[i2], 1 )
            );
          }
        }
        return this;
      }
    } )(
      function ( arr, elem ) {
        var locs  = [];
        var tmpi  = arr.indexOf( elem, 0 );
        while (
          ( tmpi ^ -1 )
          && (
            locs.push( tmpi ),
            tmpi = arr.indexOf( elem, tmpi + 1 ), 1
          )
        );
        return locs;
      }
    );
    //

#17


-4  

Array.prototype.unique =function(){
    var uniqObj={};
    for(var i=0;i< this.length;i++){
      uniqObj[this[i]]=this[i]; 
    }
    return uniqObj;
}

#1


247  

Edited

编辑

ES6 solution:

ES6解决方案:

[...new Set(a)];

Alternative:

选择:

Array.from(new Set(a));

Old response. O(n^2) (do not use it with large arrays!)

旧的回应。O(n ^ 2)(不要使用大数组!)

var arrayUnique = function(a) {
    return a.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
};

#2


47  

If you want to maintain order:

如果你想维持秩序:

arr = arr.reverse().filter(function (e, i, arr) {
    return arr.indexOf(e, i+1) === -1;
}).reverse();

Since there's no built-in reverse indexof, I reverse the array, filter out duplicates, then re-reverse it.

由于没有内置的反向索引,所以我反向数组,过滤重复的数组,然后再反向。

The filter function looks for any occurence of the element after the current index (before in the original array). If one is found, it throws out this element.

过滤器函数在当前索引(在原始数组中之前)查找元素的任何出现。如果找到一个,它会抛出这个元素。

Edit:

编辑:

Alternatively, you could use lastindexOf (if you don't care about order):

或者,您可以使用lastindexOf(如果您不关心顺序的话):

arr = arr.filter(function (e, i, arr) {
    return arr.lastIndexOf(e) === i;
});

This will keep unique elements, but only the last occurrence. This means that ['0', '1', '0'] becomes ['1', '0'], not ['0', '1'].

这将保留唯一的元素,但只保留最后的元素。这意味着[' 0 ',' 1 ',' 0 ']是[' 1 ',' 0 '),而不是(“0”,“1”)。

#3


26  

Here is an Array Prototype function:

这是一个数组原型函数:

Array.prototype.unique = function() {
    var unique = [];
    for (var i = 0; i < this.length; i++) {
        if (unique.indexOf(this[i]) == -1) {
            unique.push(this[i]);
        }
    }
    return unique;
};

#4


13  

With underscorejs

与underscorejs

_.uniq([1, 2, 1, 3, 1, 4]); //=> [1, 2, 3, 4]

#5


13  

It's 2014 now guys, and time complexity still matters!

现在是2014年了,时间的复杂性仍然很重要!

array.filter(function() {
  var seen = {};
  return function(element, index, array) {
    return !(element in seen) && (seen[element] = 1);
  };
}());

http://jsperf.com/array-filter-unique/13

http://jsperf.com/array-filter-unique/13

#6


9  

function array_unique(arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i]);
        }
    }
    return result;
}

Not a built in function. If the product list does not contain the item, add it to unique list and return unique list.

不是一个内置函数。如果产品列表不包含项目,将其添加到唯一列表并返回唯一列表。

#7


7  

There you go! You are welcome!

你走吧!你是受欢迎的!

Array.prototype.unique = function()
{
    var tmp = {}, out = [];
    for(var i = 0, n = this.length; i < n; ++i)
    {
        if(!tmp[this[i]]) { tmp[this[i]] = true; out.push(this[i]); }
    }
    return out;
}

var a = [1,2,2,7,4,1,'a',0,6,9,'a'];
var b = a.unique();
alert(a);
alert(b);

#8


3  

You can find all kinds of array unique implementations here:

你可以在这里找到所有类型的数组唯一实现:

http://jsperf.com/distinct-hash-vs-comparison/12

http://jsperf.com/distinct-hash-vs-comparison/12

http://jsperf.com/array-unique-functional

http://jsperf.com/array-unique-functional

I prefer functional styles such as:

我喜欢功能性的风格,比如:

var arr = ['lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg', 'lol', 'dfgfg', 'car', 1, 'car', 'a', 'blah', 'b', 'c', 'd', '0', '1', '1', '2', '3', '3', '3', 'crazy', 'moot', 'car', 'lol', 1, 'fdgdfg'];

var newarr = arr.reduce(function (prev, cur) {
    //console.log(prev, cur);
    if (prev.indexOf(cur) < 0) prev.push(cur);
    return prev;
}, []);

var secarr = arr.filter(function(element, index, array){
    //console.log(element, array.indexOf(element), index);
    return array.indexOf(element) >= index;
});

//reverses the order
var thirdarr = arr.filter(function (e, i, arr) {
    //console.log(e, arr.lastIndexOf(e), i);
    return arr.lastIndexOf(e) === i;
});

console.log(newarr);
console.log(secarr);
console.log(thirdarr);

#9


1  

function array_unique(nav_array) {
    nav_array = nav_array.sort(function (a, b) { return a*1 - b*1; });      
    var ret = [nav_array[0]];       
    // Start loop at 1 as element 0 can never be a duplicate
    for (var i = 1; i < nav_array.length; i++) { 
        if (nav_array[i-1] !== nav_array[i]) {              
            ret.push(nav_array[i]);             
        }       
    }
    return ret;     
}

#10


1  

This will work. Try it.

这将工作。试一试。

function getUnique(a) {
  var b = [a[0]], i, j, tmp;
  for (i = 1; i < a.length; i++) {
    tmp = 1;
    for (j = 0; j < b.length; j++) {
      if (a[i] == b[j]) {
        tmp = 0;
        break;
      }
    }
    if (tmp) {
      b.push(a[i]);
    }
  }
  return b;
}

#11


1  

I like to use this. There is nothing wrong with using the for loop, I just like using the build-in functions. You could even pass in a boolean argument for typecast or non typecast matching, which in that case you would use a for loop (the filter() method/function does typecast matching (===))

我喜欢用这个。使用for循环没有错,我只是喜欢使用内建函数。您甚至可以为类型转换或非类型转换传递一个布尔参数,在这种情况下,您将使用for循环(filter()方法/函数执行类型转换匹配(==)))

Array.prototype.unique =
function()
{
    return this.filter(
        function(val, i, arr)
        {
            return (i <= arr.indexOf(val));
        }
    );
}

#12


1  

No redundant "return" array, no ECMA5 (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;
}

#13


1  

Here is the way you can do remove duplicate values from the Array.

以下是从数组中删除重复值的方法。

function ArrNoDupe(dupArray) {
   var temp = {};
    for (var i = 0; i < dupArray.length; i++) {
         temp[dupArray[i]] = true;
         var uniqueArray = [];
       for (var k in temp)
           uniqueArray.push(k);
 return uniqueArray;
    }
}

#14


1  

Another approach is to use an object for initial storage of the array information. Then convert back. For example:

另一种方法是使用对象来初始存储数组信息。然后再转换回来。例如:

var arr = ['0','1','1','2','3','3','3'];
var obj = {};

for(var i in arr) 
    obj[i] = true;

arr = [];
for(var i in obj) 
    arr.push(i);

Variable "arr" now contains ["0", "1", "2", "3", "4", "5", "6"]

变量“加勒比海盗”现在包含(“0”、“1”、“2”、“3”、“4”、“5”、“6”)

#15


0  

Those of you who work with google closure library, have at their disposal goog.array.removeDuplicates, which is the same as unique. It changes the array itself, though.

使用谷歌闭包库的人可以使用google .array。removeduplicate,与unique相同。不过,它改变了数组本身。

#16


-1  

    //
    Array.prototype.unique =
    ( function ( _where ) {
      return function () {
        for (
          var
          i1 = 0,
          dups;
          i1 < this.length;
          i1++
        ) {
          if ( ( dups = _where( this, this[i1] ) ).length > 1 ) {
            for (
              var
              i2 = dups.length;
              --i2;
              this.splice( dups[i2], 1 )
            );
          }
        }
        return this;
      }
    } )(
      function ( arr, elem ) {
        var locs  = [];
        var tmpi  = arr.indexOf( elem, 0 );
        while (
          ( tmpi ^ -1 )
          && (
            locs.push( tmpi ),
            tmpi = arr.indexOf( elem, tmpi + 1 ), 1
          )
        );
        return locs;
      }
    );
    //

#17


-4  

Array.prototype.unique =function(){
    var uniqObj={};
    for(var i=0;i< this.length;i++){
      uniqObj[this[i]]=this[i]; 
    }
    return uniqObj;
}