如何获得数组中唯一值的列表?我是否总是必须使用第二个数组,或者是否有类似于JavaScript中Java哈希表的东西?
我将仅使用JavaScript和jQuery。不能使用其他库。
underscore.js
图书馆吗?
list.toSet
如何获得数组中唯一值的列表?我是否总是必须使用第二个数组,或者是否有类似于JavaScript中Java哈希表的东西?
我将仅使用JavaScript和jQuery。不能使用其他库。
underscore.js
图书馆吗?
list.toSet
Answers:
由于我在@Rocket答案的注释中继续进行了讨论,因此我不妨提供一个不使用任何库的示例。这需要两个新的原型函数,contains
并且unique
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.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]
console.log(uniques);
为了提高可靠性,可以contains
用MDN的indexOf
垫片代替,并检查每个元素的值indexOf
是否等于-1:文档
~a.indexOf(b) === (a.indexOf(b) == -1)
if (~a.indexOf(b)) ...
是相同的,以书面形式更长if (a.indexOf(b) == -1) ...
。
或对于那些希望与当前浏览器兼容的单行(简单和功能性)的用户:
let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);
更新18-04-2017
似乎“ Array.prototype.includes”现在在最新版本的主线浏览器中得到了广泛的支持(兼容性)
更新29-07-2015:
在浏览器中,有一些计划支持标准的“ Array.prototype.includes”方法,尽管该方法不能直接回答这个问题。通常是相关的。
用法:
["1", "1", "2", "3", "3", "1"].includes("2"); // true
// 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;
}
});
}
使用ES6语法
list = list.filter((x, i, a) => a.indexOf(x) === i)
x --> item in array
i --> index of item
a --> array reference, (in this case "list")
使用ES5语法
list = list.filter(function (x, i, a) {
return a.indexOf(x) === i;
});
浏览器兼容性:IE9 +
a.indexOf(x) === i
注意三个平等号可能会很好。
现在在ES6中,我们可以使用新引入的ES6功能
let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
let uniqueItems = Array.from(new Set(items))
或在可迭代对象上使用数组扩展语法
let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2];
let uniqueItems = [...new Set(items)];
它将返回唯一的结果。
[1, 3, 4, 5, 2, 23]
new Set
这样的(如现代角/打字稿)
let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2];
let uniqueItems = [...new Set(items)];
使用EcmaScript 2016,您可以像这样简单地进行操作。
var arr = ["a", "a", "b"];
var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];
集始终是唯一的,使用Array.from()
可以将集转换为数组。作为参考,请查看文档。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/来自 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects /组
indexOf()
答案很糟糕,因为它们是O(N ^ 2)。分散的答案是可以的,但不适用于大型阵列。这是最好的方法。
如果您想保留原始数组,
您需要第二个数组来包含第一个数组的uniqe元素,
大多数浏览器具有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;
}
如今,您可以使用ES6的Set数据类型将阵列转换为唯一的Set。然后,如果需要使用数组方法,则可以将其变回数组:
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"
var uniqueArr = [...new Set(arr)]; // ["a", "b"]
使用jQuery,这是我制作的Array唯一函数:
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]
$.uniqueArray(arr)
吗?在Array
原型中嵌入对jQuery的引用似乎是有问题的
$.uniqueArray
依赖jQuery。不太明显Array.prototype.unique
也是如此。
prototype
s一样。但是,我现在明白你的意思了。反正我会把它留在这里。
使用第二个数组的简短解决方案;
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
快速,紧凑,无嵌套循环,可与任何对象一起使用,不仅是字符串和数字,而且可以使用谓词,并且只需5行代码!
function findUnique(arr, predicate) {
var found = {};
arr.forEach(d => {
found[predicate(d)] = d;
});
return Object.keys(found).map(key => found[key]);
}
示例:按类型查找唯一项:
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'}
// ]
如果您希望它找到第一个唯一项而不是最后一个,请添加found.hasOwnPropery()进行检查。
您只需要香草JS即可使用Array.some和Array.reduce查找唯一性。使用ES2015语法,只有62个字符。
a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)
IE9 +和其他浏览器支持Array.some和Array.reduce。只需将常规功能的粗箭头功能更改为在不支持ES2015语法的浏览器中即可支持。
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/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects /阵列/减少
上述大多数解决方案具有很高的运行时复杂度。
这是使用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];
注意:
此解决方案不依赖于减少。这个想法是创建一个对象映射并将唯一的映射到数组中。
ES6方式:
const uniq = (arr) => (arr.filter((item, index, arry) => (arry.indexOf(item) === index)));
您可以输入重复的数组,下面的方法将返回包含唯一元素的数组。
function getUniqueArray(array){
var uniqueArray = [];
if (array.length > 0) {
uniqueArray[0] = array[0];
}
for(var i = 0; i < array.length; i++){
var isExist = false;
for(var j = 0; j < uniqueArray.length; j++){
if(array[i] == uniqueArray[j]){
isExist = true;
break;
}
else{
isExist = false;
}
}
if(isExist == false){
uniqueArray[uniqueArray.length] = array[i];
}
}
return uniqueArray;
}
我已经在纯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);
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"]
如果您不必担心旧版浏览器,那么这正是Sets的目标。
Set对象使您可以存储任何类型的唯一值,无论是原始值还是对象引用。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set
const set1 = new Set([1, 2, 3, 4, 5, 1]);
// returns Set(5) {1, 2, 3, 4, 5}
这是一种具有可自定义equals
功能的方法,可用于基元和自定义对象:
Array.prototype.pushUnique = function(element, equalsPredicate = (l, r) => l == r) {
let res = !this.find(item => equalsPredicate(item, element))
if(res){
this.push(element)
}
return res
}
用法:
//with custom equals for objects
myArrayWithObjects.pushUnique(myObject, (left, right) => left.id == right.id)
//with default equals for primitives
myArrayWithPrimitives.pushUnique(somePrimitive)
我的答案使用Array.filter
和Array.indexOf
方法来获得唯一值
array.filter((value, index, self)=>self.indexOf(value)===index)
我在网站上看到了这种方法,但是它们的代码与此处看起来不同。我将代码简化为一行,并将其发布在此处,以便有人从中受益
注意:我的方法与Josh发布的那支班轮相似或相同。我将其保留在此处,因为变量名在我的代码中很容易说明。
我只是在考虑是否可以使用线性搜索来消除重复项:
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:
<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>
这是该问题的一种解决方案:
var seriesValues = [120, 120, 120, 120];
seriesValues = seriesValues.filter((value, index, seriesValues) => (seriesValues.slice(0, index)).indexOf(value) === -1);
console.log(seriesValues);
复制此粘贴到浏览器控制台,并获得结果,哟:-)
我有内置的JQuery Unique函数。
uniqueValues= jQuery.unique( duplicateValues );
有关更多信息,请参考jquery API文档。