简体   繁体   中英

How to compare multiple arrays and return an array with unique values in javascript?

I would like to compare multiple array and finally have an array that contain all unique values from different array. I tried to:

1,Use the filter method to compare the difference between 2 arrays

2,Call a for loop to input the arrays into the filter method

and the code is as follows

function diffArray(arr1, arr2) {
  function filterfunction (arr1, arr2) {
    return arr1.filter(function(item) {
      return arr2.indexOf(item) === -1;
    });
  }  
  return filterfunction (arr1,arr2).concat(filterfunction(arr2,arr1));
}

function extractArray() {
  var args = Array.prototype.slice.call(arguments);
  for (var i =0; i < args.length; i++) {
    diffArray(args[i],args[i+1]);
  }
}

extractArray([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]);

However it does not work and return the error message "Cannot read property 'indexOf' of underfined" .... What's wrong with the logic and what should I change to make it works?

Many thanks for your help in advance!

Re: For all that mark this issue as duplicated ... what I am looking for, is a solution that can let me to put as many arrays as I want for input and reduce all the difference (eg input 10000 arrays and return 1 array for unique value), but not only comparing 2 arrays .. The solutions that I have seen are always with 2 arrays only.

I don't use filters or anything of the sort but it will get the job done. I first create an empty array and concat the next array to it. Then I pass it to delete the duplicates and return the newly "filtered" array back for use.

function deleteDuplicates(a){
    for(var i = a.length - 1; i >= 0; i--){
        if(a.indexOf(a[i]) !== i){
            a.splice(i, 1);
        }
    }
    return a;
}

function extractArray() {
    var args = Array.prototype.slice.call(arguments), arr = [];

    for (var i = 0; i < args.length; i++) {
        arr = deleteDuplicates(arr.concat(args[i]));
    }

    return arr;
}

var arr = extractArray([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]);

console.log(arr) //[3, 2, 5, 1, 7, 4, 6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM