如何在数组中获取唯一值

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

How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?

如何在数组中获取唯一值的列表?我是否总是需要使用第二个数组,还是在JavaScript中有类似于java的hashmap的东西?

I am going to be using JavaScript and jQuery only. No additional libraries can be used.

我将只使用JavaScript和jQuery。不能使用其他库。

25 个解决方案

#1


89  

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

既然我在@Rocket的回答的评论中继续讨论这个问题,我不妨提供一个不使用库的例子。这需要两个新的原型函数,包含和唯一。

Array.prototype.contains = function(v) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] === v) return true;
    }
    return false;
};

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

You can then do:

你可以做的:

var duplicates = [1,3,4,2,1,2,3,8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

为了获得更高的可靠性,您可以使用MDN的shim索引替换contains,并检查每个元素的索引是否等于-1:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

#2


141  

Or for those looking for a one-liner (simple and functional), compatible with current browsers:

或者对于那些想要寻找一种简单实用的、与当前浏览器兼容的一行程序的人:

var a = ["1", "1", "2", "3", "3", "1"];
var unique = a.filter(function(item, i, ar){ return ar.indexOf(item) === i; });

Update 18-04-17

更新18-04-17

It appears as though 'Array.prototype.includes' now has widespread support in the latest versions of the mainline browsers (compatibility)

它看起来像是“Array.prototype”。包括'现在已经在最新版本的主流浏览器中得到了广泛的支持(兼容性)

Update 29/07/2015:

更新29/07/2015:

There are plans in the works for browsers to support a standardized 'Array.prototype.includes' method, which although does not directly answer this question; is often related.

目前有一些浏览器计划支持标准化的“Array.prototype”。包含的方法,虽然没有直接回答这个问题;往往是相关的。

Usage:

用法:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill (browser support, source from mozilla):

Pollyfill(浏览器支持,来自mozilla的源代码):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

#3


48  

One Liner, Pure JavaScript

With ES6 syntax

与ES6语法

list = list.filter((x, i, a) => a.indexOf(x) == i)

列表=。filter(x, i, a) => a. indexof (x) = i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

如何在数组中获取唯一值

With ES5 syntax

与ES5的语法

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) == i; 
});

Browser Compatibility: IE9+

IE9浏览器兼容性:+

#4


33  

Here's a much cleaner solution for ES6 that I see isn't included here. It uses the Set and the spread operator: ...

这里有一个更干净的ES6解决方案,我看到这里没有包含。它使用集合和扩展操作符:…

var a = [1, 1, 2];

[... new Set(a)]

Which returns [1, 2]

它返回[1,2]

#5


13  

If you want to leave the original array intact,

如果你想让原始数组保持完整,

you need a second array to contain the uniqe elements of the first-

您需要第二个数组来包含第一个-的uniqe元素

Most browsers have Array.prototype.filter:

大多数浏览器Array.prototype.filter:

var unique= array1.filter(function(itm, i){
    return array1.indexOf(itm)== i; 
    // returns true for only the first instance of itm
});


//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
 Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
        if(!i || typeof i!= 'number') i= 0;
        var L= this.length;
        while(i<L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }

#6


9  

These days, you can use ES6's Set data type to convert your array to a unique Set. Then, if you need to use array methods, you can turn it back into an Array:

现在,你可以使用ES6的Set数据类型将你的数组转换成一个唯一的集合。如果你需要使用array方法,你可以将它转换回一个array:

var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"

#7


7  

Using EcmaScript 2016 you can simply do it like this.

使用EcmaScript 2016,您只需这样做。

 var arr = ["a", "a", "b"];
 var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];

Sets are always unique, and using Array.from() you can convert a Set to an array. For reference have a look at the documentations.

集合总是唯一的,使用array. from()可以将集合转换为数组。为了便于参考,请参阅文件。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

#8


6  

Short and sweet solution using second array;

采用第二阵列的短而甜的解决方案;

var axes2=[1,4,5,2,3,1,2,3,4,5,1,3,4];

    var distinct_axes2=[];

    for(var i=0;i<axes2.length;i++)
        {
        var str=axes2[i];
        if(distinct_axes2.indexOf(str)==-1)
            {
            distinct_axes2.push(str);
            }
        }
    console.log("distinct_axes2 : "+distinct_axes2); // distinct_axes2 : 1,4,5,2,3

#9


4  

Using jQuery, here's an Array unique function I made:

使用jQuery,我做了一个数组唯一函数:

Array.prototype.unique = function () {
    var arr = this;
    return $.grep(arr, function (v, i) {
        return $.inArray(v, arr) === i;
    });
}

console.log([1,2,3,1,2,3].unique()); // [1,2,3]

#10


3  

Not native in Javascript, but plenty of libraries have this method.

在Javascript中不是原生的,但是很多库都有这种方法。

Underscore.js's _.uniq(array) (link) works quite well (source).

下划线。js的_.uniq(数组)(链接)工作得很好(源代码)。

#11


3  

You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.

你只需要普通的JS就可以找到带有数组的uniques。一些和Array.reduce。使用ES2015语法,它只有62个字符。

a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)

Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.

数组中。一些和数组。减少在IE9+和其他浏览器中得到支持。只需要在不支持ES2015语法的浏览器中更改常规函数的fat arrow函数即可。

var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
    // .some stops on the first time the function returns true                
    return (b.some(function(w){ return w === v; }) ?  
      // if there's a match, return the array "c"
      c :     
      // if there's no match, then add to the end and return the entire array                                        
      c.concat(v)}),                                  
  // the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
  b);                                                 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

#12


3  

Majority of the solutions above have a high run time complexity.

以上大多数解决方案都具有很高的运行时间复杂度。

Here is the solution that uses reduce and can do the job in O(n) time.

这是使用reduce的解决方案,可以在O(n)时间内完成这项工作。

Array.prototype.unique = Array.prototype.unique || function() {
        var arr = [];
	this.reduce(function (hash, num) {
		if(typeof hash[num] === 'undefined') {
			hash[num] = 1; 
			arr.push(num);
		}
		return hash;
	}, {});
	return arr;
}
    
var myArr = [3,1,2,3,3,3];
console.log(myArr.unique()); //[3,1,2];

Note:

注意:

This solution is not dependent on reduce. The idea is to create an object map and push unique ones into the array.

这个解决方案不依赖于减少。其想法是创建一个对象映射并将唯一的映射推入数组。

#13


2  

Fast, compact, no nested loops, works with any object not just strings and numbers, takes a predicate, and only 5 lines of code!!

快速,紧凑,没有嵌套循环,适用于任何对象,不只是字符串和数字,使用谓词,只有5行代码!

function findUnique(arr, predicate) {
  var found = {};
  arr.forEach(d => {
    found[predicate(d)] = d;
  });
  return Object.keys(found).map(key => found[key]); 
}

Example: To find unique items by type:

示例:按类型查找惟一项:

var things = [
  { name: 'charm', type: 'quark'},
  { name: 'strange', type: 'quark'},
  { name: 'proton', type: 'boson'},
];

var result = findUnique(things, d => d.type);
//  [
//    { name: 'charm', type: 'quark'},
//    { name: 'proton', type: 'boson'}
//  ] 

If you want it to find the first unique item instead of the last add a found.hasOwnPropery() check in there.

如果您想让它找到第一个唯一项而不是最后一个,那么添加一个find . hasownpropery()。

#14


1  

Now in ES6 we can use the newly introduced ES6 function

在ES6中,我们可以使用新引入的ES6函数

var items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
var uniqueItems = Array.from(new Set(items))

It will return the unique result.

它将返回唯一的结果。

[1, 3, 4, 5, 2, 23]

#15


0  

The only problem with the solutions given so far is efficiency. If you are concerned about that (and you probably should) you need to avoid nested loops: for * for, filter * indexOf, grep * inArray, they all iterate the array multiple times. You can implement a single loop with solutions like this or this

到目前为止给出的解决方案的唯一问题是效率。如果您对此感到担心(您可能应该担心),那么您需要避免嵌套循环:for * for、filter * indexOf、grep * inArray,它们都要对数组进行多次迭代。您可以使用这样或那样的解决方案实现一个单循环

#16


0  

Another thought of this question. Here is what I did to achieve this with fewer code.

这个问题的另一个想法。下面是我用更少的代码实现的。

var distinctMap = {};
var testArray = ['John', 'John', 'Jason', 'Jason'];
for (var i = 0; i < testArray.length; i++) {
  var value = testArray[i];
  distinctMap[value] = '';
};
var unique_values = Object.keys(distinctMap);

#17


0  

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

#18


0  

function findUnique(arr) {
    var result = [];
    arr.forEach(function (d) {
        if (result.indexOf(d) === -1)
            result.push(d);
    });
    return result;
}

var unique = findUnique([1, 2, 3, 1, 2, 1, 4]); // [1,2,3,4]

#19


0  

ES6 way:

ES6道:

const uniq = (arr) => (arr.filter((item, index, arry) => (arry.indexOf(item) === index)));

#20


0  

I have tried this problem in pure JS. I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value

我用纯JS尝试过这个问题。我遵循了以下步骤1。对给定的数组进行排序,2。循环遍历排序数组,3。用当前值验证先前值和下一个值

// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];

//sort the given array
inpArr.sort(function(a, b){
    return a-b;
});

var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
    //check previous and next value 
  if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
        finalArr.push(inpArr[i]);
  }
}
console.log(finalArr);

Demo

演示

#21


0  

function findUniques(arr){
  let uniques = []
  arr.forEach(n => {
    if(!uniques.includes(n)){
      uniques.push(n)
    }       
  })
  return uniques
}

let arr = ["3", "3", "4", "4", "4", "5", "7", "9", "b", "d", "e", "f", "h", "q", "r", "t", "t"]

findUniques(arr)
// ["3", "4", "5", "7", "9", "b", "d", "e", "f", "h", "q", "r", "t"]

#22


0  

Having in mind that indexOf will return the first occurence of an element, you can do something like this:

考虑到indexOf将返回一个元素的第一次出现,您可以这样做:

Array.prototype.unique = function(){
        var self = this;
        return this.filter(function(elem, index){
            return self.indexOf(elem) === index;
        })
    }

#23


-1  

I was just thinking if we can use linear search to eliminate the duplicates:

我在想如果我们可以用线性搜索来消除重复:

JavaScript:
function getUniqueRadios() {

var x=document.getElementById("QnA");
var ansArray = new Array();
var prev;


for (var i=0;i<x.length;i++)
  {
    // Check for unique radio button group
    if (x.elements[i].type == "radio")
    {
            // For the first element prev will be null, hence push it into array and set the prev var.
            if (prev == null)
            {
                prev = x.elements[i].name;
                ansArray.push(x.elements[i].name);
            } else {
                   // We will only push the next radio element if its not identical to previous.
                   if (prev != x.elements[i].name)
                   {
                       prev = x.elements[i].name;
                       ansArray.push(x.elements[i].name);
                   }
            }
    }

  }

   alert(ansArray);

}

}

HTML:

HTML:

<body>

<form name="QnA" action="" method='post' ">

<input type="radio"  name="g1" value="ANSTYPE1"> good </input>
<input type="radio" name="g1" value="ANSTYPE2"> avg </input>

<input type="radio"  name="g2" value="ANSTYPE3"> Type1 </input>
<input type="radio" name="g2" value="ANSTYPE2"> Type2 </input>


<input type="submit" value='SUBMIT' onClick="javascript:getUniqueRadios()"></input>


</form>
</body>

#24


-1  

Here is the one liner solution to the problem:

这里有一个问题的线性解决方案:

var seriesValues = [120, 120, 120, 120];
seriesValues = seriesValues.filter((value, index, seriesValues) => (seriesValues.slice(0, index)).indexOf(value) === -1);
console.log(seriesValues);

Copy paste this to browsers console and get the results, yo :-)

复制粘贴到浏览器控制台并得到结果,哟:-)

#25


-2  

i have inbuilt JQuery Unique function.

我内置了JQuery唯一的函数。

uniqueValues= jQuery.unique( duplicateValues );

For more you can refer to the jquery API Documentations.

更多信息,请参考jquery API文档。

http://api.jquery.com/jquery.unique/

http://api.jquery.com/jquery.unique/

#1


89  

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

既然我在@Rocket的回答的评论中继续讨论这个问题,我不妨提供一个不使用库的例子。这需要两个新的原型函数,包含和唯一。

Array.prototype.contains = function(v) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] === v) return true;
    }
    return false;
};

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

You can then do:

你可以做的:

var duplicates = [1,3,4,2,1,2,3,8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

为了获得更高的可靠性,您可以使用MDN的shim索引替换contains,并检查每个元素的索引是否等于-1:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

#2


141  

Or for those looking for a one-liner (simple and functional), compatible with current browsers:

或者对于那些想要寻找一种简单实用的、与当前浏览器兼容的一行程序的人:

var a = ["1", "1", "2", "3", "3", "1"];
var unique = a.filter(function(item, i, ar){ return ar.indexOf(item) === i; });

Update 18-04-17

更新18-04-17

It appears as though 'Array.prototype.includes' now has widespread support in the latest versions of the mainline browsers (compatibility)

它看起来像是“Array.prototype”。包括'现在已经在最新版本的主流浏览器中得到了广泛的支持(兼容性)

Update 29/07/2015:

更新29/07/2015:

There are plans in the works for browsers to support a standardized 'Array.prototype.includes' method, which although does not directly answer this question; is often related.

目前有一些浏览器计划支持标准化的“Array.prototype”。包含的方法,虽然没有直接回答这个问题;往往是相关的。

Usage:

用法:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill (browser support, source from mozilla):

Pollyfill(浏览器支持,来自mozilla的源代码):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

#3


48  

One Liner, Pure JavaScript

With ES6 syntax

与ES6语法

list = list.filter((x, i, a) => a.indexOf(x) == i)

列表=。filter(x, i, a) => a. indexof (x) = i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

如何在数组中获取唯一值

With ES5 syntax

与ES5的语法

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) == i; 
});

Browser Compatibility: IE9+

IE9浏览器兼容性:+

#4


33  

Here's a much cleaner solution for ES6 that I see isn't included here. It uses the Set and the spread operator: ...

这里有一个更干净的ES6解决方案,我看到这里没有包含。它使用集合和扩展操作符:…

var a = [1, 1, 2];

[... new Set(a)]

Which returns [1, 2]

它返回[1,2]

#5


13  

If you want to leave the original array intact,

如果你想让原始数组保持完整,

you need a second array to contain the uniqe elements of the first-

您需要第二个数组来包含第一个-的uniqe元素

Most browsers have Array.prototype.filter:

大多数浏览器Array.prototype.filter:

var unique= array1.filter(function(itm, i){
    return array1.indexOf(itm)== i; 
    // returns true for only the first instance of itm
});


//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
 Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
        if(!i || typeof i!= 'number') i= 0;
        var L= this.length;
        while(i<L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }

#6


9  

These days, you can use ES6's Set data type to convert your array to a unique Set. Then, if you need to use array methods, you can turn it back into an Array:

现在,你可以使用ES6的Set数据类型将你的数组转换成一个唯一的集合。如果你需要使用array方法,你可以将它转换回一个array:

var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"

#7


7  

Using EcmaScript 2016 you can simply do it like this.

使用EcmaScript 2016,您只需这样做。

 var arr = ["a", "a", "b"];
 var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];

Sets are always unique, and using Array.from() you can convert a Set to an array. For reference have a look at the documentations.

集合总是唯一的,使用array. from()可以将集合转换为数组。为了便于参考,请参阅文件。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

#8


6  

Short and sweet solution using second array;

采用第二阵列的短而甜的解决方案;

var axes2=[1,4,5,2,3,1,2,3,4,5,1,3,4];

    var distinct_axes2=[];

    for(var i=0;i<axes2.length;i++)
        {
        var str=axes2[i];
        if(distinct_axes2.indexOf(str)==-1)
            {
            distinct_axes2.push(str);
            }
        }
    console.log("distinct_axes2 : "+distinct_axes2); // distinct_axes2 : 1,4,5,2,3

#9


4  

Using jQuery, here's an Array unique function I made:

使用jQuery,我做了一个数组唯一函数:

Array.prototype.unique = function () {
    var arr = this;
    return $.grep(arr, function (v, i) {
        return $.inArray(v, arr) === i;
    });
}

console.log([1,2,3,1,2,3].unique()); // [1,2,3]

#10


3  

Not native in Javascript, but plenty of libraries have this method.

在Javascript中不是原生的,但是很多库都有这种方法。

Underscore.js's _.uniq(array) (link) works quite well (source).

下划线。js的_.uniq(数组)(链接)工作得很好(源代码)。

#11


3  

You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.

你只需要普通的JS就可以找到带有数组的uniques。一些和Array.reduce。使用ES2015语法,它只有62个字符。

a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)

Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.

数组中。一些和数组。减少在IE9+和其他浏览器中得到支持。只需要在不支持ES2015语法的浏览器中更改常规函数的fat arrow函数即可。

var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
    // .some stops on the first time the function returns true                
    return (b.some(function(w){ return w === v; }) ?  
      // if there's a match, return the array "c"
      c :     
      // if there's no match, then add to the end and return the entire array                                        
      c.concat(v)}),                                  
  // the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
  b);                                                 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

#12


3  

Majority of the solutions above have a high run time complexity.

以上大多数解决方案都具有很高的运行时间复杂度。

Here is the solution that uses reduce and can do the job in O(n) time.

这是使用reduce的解决方案,可以在O(n)时间内完成这项工作。

Array.prototype.unique = Array.prototype.unique || function() {
        var arr = [];
	this.reduce(function (hash, num) {
		if(typeof hash[num] === 'undefined') {
			hash[num] = 1; 
			arr.push(num);
		}
		return hash;
	}, {});
	return arr;
}
    
var myArr = [3,1,2,3,3,3];
console.log(myArr.unique()); //[3,1,2];

Note:

注意:

This solution is not dependent on reduce. The idea is to create an object map and push unique ones into the array.

这个解决方案不依赖于减少。其想法是创建一个对象映射并将唯一的映射推入数组。

#13


2  

Fast, compact, no nested loops, works with any object not just strings and numbers, takes a predicate, and only 5 lines of code!!

快速,紧凑,没有嵌套循环,适用于任何对象,不只是字符串和数字,使用谓词,只有5行代码!

function findUnique(arr, predicate) {
  var found = {};
  arr.forEach(d => {
    found[predicate(d)] = d;
  });
  return Object.keys(found).map(key => found[key]); 
}

Example: To find unique items by type:

示例:按类型查找惟一项:

var things = [
  { name: 'charm', type: 'quark'},
  { name: 'strange', type: 'quark'},
  { name: 'proton', type: 'boson'},
];

var result = findUnique(things, d => d.type);
//  [
//    { name: 'charm', type: 'quark'},
//    { name: 'proton', type: 'boson'}
//  ] 

If you want it to find the first unique item instead of the last add a found.hasOwnPropery() check in there.

如果您想让它找到第一个唯一项而不是最后一个,那么添加一个find . hasownpropery()。

#14


1  

Now in ES6 we can use the newly introduced ES6 function

在ES6中,我们可以使用新引入的ES6函数

var items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
var uniqueItems = Array.from(new Set(items))

It will return the unique result.

它将返回唯一的结果。

[1, 3, 4, 5, 2, 23]

#15


0  

The only problem with the solutions given so far is efficiency. If you are concerned about that (and you probably should) you need to avoid nested loops: for * for, filter * indexOf, grep * inArray, they all iterate the array multiple times. You can implement a single loop with solutions like this or this

到目前为止给出的解决方案的唯一问题是效率。如果您对此感到担心(您可能应该担心),那么您需要避免嵌套循环:for * for、filter * indexOf、grep * inArray,它们都要对数组进行多次迭代。您可以使用这样或那样的解决方案实现一个单循环

#16


0  

Another thought of this question. Here is what I did to achieve this with fewer code.

这个问题的另一个想法。下面是我用更少的代码实现的。

var distinctMap = {};
var testArray = ['John', 'John', 'Jason', 'Jason'];
for (var i = 0; i < testArray.length; i++) {
  var value = testArray[i];
  distinctMap[value] = '';
};
var unique_values = Object.keys(distinctMap);

#17


0  

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

#18


0  

function findUnique(arr) {
    var result = [];
    arr.forEach(function (d) {
        if (result.indexOf(d) === -1)
            result.push(d);
    });
    return result;
}

var unique = findUnique([1, 2, 3, 1, 2, 1, 4]); // [1,2,3,4]

#19


0  

ES6 way:

ES6道:

const uniq = (arr) => (arr.filter((item, index, arry) => (arry.indexOf(item) === index)));

#20


0  

I have tried this problem in pure JS. I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value

我用纯JS尝试过这个问题。我遵循了以下步骤1。对给定的数组进行排序,2。循环遍历排序数组,3。用当前值验证先前值和下一个值

// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];

//sort the given array
inpArr.sort(function(a, b){
    return a-b;
});

var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
    //check previous and next value 
  if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
        finalArr.push(inpArr[i]);
  }
}
console.log(finalArr);

Demo

演示

#21


0  

function findUniques(arr){
  let uniques = []
  arr.forEach(n => {
    if(!uniques.includes(n)){
      uniques.push(n)
    }       
  })
  return uniques
}

let arr = ["3", "3", "4", "4", "4", "5", "7", "9", "b", "d", "e", "f", "h", "q", "r", "t", "t"]

findUniques(arr)
// ["3", "4", "5", "7", "9", "b", "d", "e", "f", "h", "q", "r", "t"]

#22


0  

Having in mind that indexOf will return the first occurence of an element, you can do something like this:

考虑到indexOf将返回一个元素的第一次出现,您可以这样做:

Array.prototype.unique = function(){
        var self = this;
        return this.filter(function(elem, index){
            return self.indexOf(elem) === index;
        })
    }

#23


-1  

I was just thinking if we can use linear search to eliminate the duplicates:

我在想如果我们可以用线性搜索来消除重复:

JavaScript:
function getUniqueRadios() {

var x=document.getElementById("QnA");
var ansArray = new Array();
var prev;


for (var i=0;i<x.length;i++)
  {
    // Check for unique radio button group
    if (x.elements[i].type == "radio")
    {
            // For the first element prev will be null, hence push it into array and set the prev var.
            if (prev == null)
            {
                prev = x.elements[i].name;
                ansArray.push(x.elements[i].name);
            } else {
                   // We will only push the next radio element if its not identical to previous.
                   if (prev != x.elements[i].name)
                   {
                       prev = x.elements[i].name;
                       ansArray.push(x.elements[i].name);
                   }
            }
    }

  }

   alert(ansArray);

}

}

HTML:

HTML:

<body>

<form name="QnA" action="" method='post' ">

<input type="radio"  name="g1" value="ANSTYPE1"> good </input>
<input type="radio" name="g1" value="ANSTYPE2"> avg </input>

<input type="radio"  name="g2" value="ANSTYPE3"> Type1 </input>
<input type="radio" name="g2" value="ANSTYPE2"> Type2 </input>


<input type="submit" value='SUBMIT' onClick="javascript:getUniqueRadios()"></input>


</form>
</body>

#24


-1  

Here is the one liner solution to the problem:

这里有一个问题的线性解决方案:

var seriesValues = [120, 120, 120, 120];
seriesValues = seriesValues.filter((value, index, seriesValues) => (seriesValues.slice(0, index)).indexOf(value) === -1);
console.log(seriesValues);

Copy paste this to browsers console and get the results, yo :-)

复制粘贴到浏览器控制台并得到结果,哟:-)

#25


-2  

i have inbuilt JQuery Unique function.

我内置了JQuery唯一的函数。

uniqueValues= jQuery.unique( duplicateValues );

For more you can refer to the jquery API Documentations.

更多信息,请参考jquery API文档。

http://api.jquery.com/jquery.unique/

http://api.jquery.com/jquery.unique/