获取 Common 和 Uniques 元素比较 Javascript 中的两个或多个数组

Get the Common and Uniques Elements Comparing two or more arrays in Javascript

首先我检查了很多 post,像这样:

Finding matches between multiple JavaScript Arrays

How to merge two arrays in Javascript and de-duplicate items

Unique values in an array

所有这些都可以正常工作,但只适用于包含整数或字符串的数组,我需要它可以满足您的任何需求。

我有两个数组,想在一个新数组中存储唯一元素,在另一个数组中存储公共元素。 这些要素可能是;变量、数组、字符串、散列(对象)函数、整数、浮点数或布尔值

并且可能永远不会成为数组中的重复值。 使用纯 JS 会很棒

而且我不关心 IE(但我猜对其他人来说会很好),所以如果有新的 ES6 方式,我会喜欢它,我更关心性能 :)

// Some values that gonna be inside the array1 & array2
function random(){};
var a = 5,
    b = {};


// The Arrays
var array1 = [0,1,2,3, "HeLLo", "hello", 55.32, 55.550, {key: "value", keyWithArray: [1,2,3]}, random, a, b];
var array2 = [2,3, "hello", "Hello", 55.32, 55.551, {key: "value", keyWithArray: [1,2,3]}, b];



// The Unique Array should be all the elements that array1 have and array2 haven't
var uniqueArray = [0, 1, "HeLLo", 55.550, random, a];


// The commonArray should the common elements in both arrays (array1 and array2)
var commonArray = [2,3, "hello", 55.32, {key: "value", keyWithArray: [1,2,3]}, b]




// I try something like this but doesn't work
var uniqueArray = array1.filter(function(val) { return array2.indexOf(val) == -1; });
console.log(uniqueArray);

据我了解,您基本上是想对两个数组执行一些设置操作。我的建议是首先从您的两个数组构建一个更合适的数据结构,因为要执行诸如获取两者的交集之类的操作,您必须执行 O(n²) 算法。 应该这样做:

// convert a plain array that has values of mixed types to and object
// where the keys are the values in plain form in case of strings, scalars or functions, or serialized objects in
// case of objects and arrays, and where the values are the unaltered values of the array.
var _toObject = function(arr) {
    var obj = {};
    for (var i=0 ; i<arr.length ; i++) {
        var el = arr[i];
        var type = typeof el;
        if (type !== 'object') { // scalars, strings and functions can be used as keys to an array
            obj[el] = el;
        }
        else { // objects and arrays have to be serialized in order to be used as keys
            obj[JSON.stringify(el)] = el;
        }
    };
    return obj;
};


var objArray1 = _toObject(array1);
var objArray2 = _toObject(array2);

var uniqueArray = [];
var commonArray = [];
for (var i in objArray1) {
    if (i in objArray2) {
        commonArray.push(objArray1[i]); // push the common elements

        delete objArray2[i]; // delete so in the end objArray2 will only have unique elements
    }
    else {
        uniqueArray.push(objArray1[i]); // push unique element from objArray1
    }
}

for (var i in objArray2) { // now objArray2 has only unique values, just append then to uniqueArray
    uniqueArray.push(objArray2[i])
}

console.log('Unique array', uniqueArray);
console.log('Common array', commonArray);

这应该会给你想要的结果:

bash-4.2$ node test.js 
Unique array [ 0, 1, 5, 'HeLLo', 55.55, [Function: random], 'Hello', 55.551 ]
Common array [ 2, 3, 'hello', 55.32, { key: 'value', keyWithArray: [1, 2, 3 ] }, {}]