javascript 从两个数组中获取唯一值并将它们放入另一个数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15912538/
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-10-27 02:33:40  来源:igfitidea点击:

Get the unique values from two arrays and put them in another array

javascriptarrays

提问by sanchitkhanna26

I have two arrays in javascript -:

我在javascript中有两个数组-:

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];

I need to a method to get the unique from two arrays and put them in array3 Array3should be -:

我需要一种从两个数组中获取唯一值并将它们放入 array3 的方法 Array3应该是 -:

var array3 = ['1','100'];

Thanks for help.

感谢帮助。

回答by Bart

var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });

MDN on Array#filter: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

Array#filter 上的 MDN:https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

Includes a polyfill for older browsers.

包括用于旧浏览器的 polyfill。

回答by Hedley Smith

With a bit of ES6 magic it can be fairly concise. Note that we need to check both ways around in case there are unique items in either array.

加上一点 ES6 魔法,它可以相当简洁。请注意,如果任一数组中都有唯一项,我们需要检查两种方式。

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 3, 8];

let unique1 = arr1.filter((o) => arr2.indexOf(o) === -1);
let unique2 = arr2.filter((o) => arr1.indexOf(o) === -1);

const unique = unique1.concat(unique2);

console.log(unique);
// >> [2, 4, 5, 8]

回答by LemonCool

var unique = [];
for(var i = 0; i < array1.length; i++){
    var found = false;

    for(var j = 0; j < array2.length; j++){ // j < is missed;
     if(array1[i] == array2[j]){
      found = true;
      break; 
    }
   }
   if(found == false){
   unique.push(array1[i]);
  }
}

UPDATEThe original post works but is not very fast, this implementation is a lot faster, this example uses only one array, but in the function you can easily pass any additional arrays to combine.

UPDATE原来的帖子有效但不是很快,这个实现要快很多,这个例子只使用一个数组,但在函数中你可以轻松地传递任何额外的数组来组合。

only a simple error check is done and more should be in place, use at own discretion, meant as working example only.

只完成了一个简单的错误检查,更多的应该到位,自行决定使用,仅作为工作示例。

function Unique(array) {
var tmp = [];
var result = [];

if (array !== undefined /* any additional error checking */ ) {
  for (var i = 0; i < array.length; i++) {
    var val = array[i];

    if (tmp[val] === undefined) {
       tmp[val] = true;
       result.push(val);
     }

    }
  }

  return result;
}

var unique = Unique([1, 2, 2, 6, 8, 5, 6, 8]);

Additionally this can be implemented as prototype of the Array object, changing the signature to

此外,这可以实现为 Array 对象的原型,将签名更改为

Array.prototype.Unique = function() {
    var array = this;
    ...
}

and can be called like this:

并且可以这样调用:

var unique = [1, 2, 2, 6, 8, 5, 6, 8].Unique();

回答by mzedeler

Something like this

像这样的东西

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];
var o = {};
for(var i in array1) {
    o[i] = 1;
}
for(var i in array2) {
    o[i] = 0;
}
var array3 = [];
for(var i in o) {
    if(o[i] == 1) {
        array3.push(i);
    }
}

回答by Tahmid Sajjad Chowdhury

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];


var newArr,temp,temp1;


    temp=array1.filter(function(el) 
              {
                return arr2.indexOf(el) == -1; 

              });

    temp1=array2.filter(function(el) 
              {
                return arr1.indexOf(el) == -1; 

              });

  newArr=temp.concat(temp1);


  return newArr;

}

回答by Ray Wadkins

Similar to above but will work with more than two arrays

与上面类似,但适用于两个以上的数组

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];
var i = 0;
var hist = {};
var array3 = [];

buildhist(array1);
buildhist(array2);

for (i in hist) {
    if (hist[i] === 1) {
        array3.push(i);
    }
}

console.log(array3);

function buildhist(arr) {
    var i;
    for (i = arr.length - 1; i >= 0; i--) {
        if (hist[arr[i]] === undefined) {
            hist[arr[i]] = 0;
        }
        hist[arr[i]]++;
    }
}

回答by kkemple

var array3 = array1.concat(array2);

array3 = array3.sort(function(a, b) { return a > b; });
array3 = array3.filter(function(num, index) { return num !== array3[index + 1]; });

array3will have only unique values

array3将只有唯一值

this also does the job in two loops which is pretty inexpensive, it should be noted that sort() and filter() are ECMA5 functions and not supported in older browsers, also i usually use a library like underscore so i don't have rewrite these functions for each project i work on, underscore has a .unique() method which obviously is less code and more clearly states the intention of the operation

这也可以在两个非常便宜的循环中完成工作,应该注意的是 sort() 和 filter() 是 ECMA5 函数,旧浏览器不支持,而且我通常使用像 underscore 这样的库,所以我没有重写我从事的每个项目的这些功能,下划线都有一个 .unique() 方法,它显然是更少的代码,更清楚地说明了操作的意图