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

时间:2015-12-09 16:11:49

标签: javascript arrays performance comparison

首先,我检查了很多帖子,如下:

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);

1 个答案:

答案 0 :(得分:1)

据我所知,你基本上想要对你的两个阵列执行一些设置操作。我的建议是首先从你的两个数组中构建一个更合适的数据结构,因为做一些事情就像获得两者的交集一样,你必须做一个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 ] }, {}]