简体   繁体   中英

extract non duplicates from two arrays JavaScript

Consider below code

I have two arrays with data and need the values that are not present.

var stores = ["1", "2", "3", "4", "5"];
var favStores = ["2", "4"];

outer: for (var i = 0; i < stores.length; i++) {
    for (var j = 0; j < favStores.length; j++) {
        if (stores[i] != favStores[j]) {
            document.write('Stores I : ' + stores[i]);
            document.write('<br>');
            document.write('Fav Stores j : ' + favStores[j]);
            document.write('<br>');
            alert('Match Found' + stores[i]);
            //continue outer;
        }
    }
}

I need my output as

1,3,5 in a new array.

This way:

var stores = ["1", "2", "3", "4", "5"];
var favStores = ["2", "4"];

var output = stores.filter(function(i){
      return favStores.indexOf(i)==-1;
});   

// output is ["1", "3", "5"]

What you need is the difference between the two arrays. Libraries like lodash have that feature but if you want to build your own you can use the following:

var stores = ["1", "2", "3 ", "4", "5"],
    favStores = ["2", "4"];

function diff(a, b) {
  var results = [];
  for(var i = 0; i < a.length; i++) {
    if(b.indexOf(a[i]) < 0)
      results.push(a[i]);
  }
  return results;
}

console.log(diff(stores, favStores));

Note that you could use forEach to traverse the array but I am just being legacy proof here.

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