1

Question: How can I elegantly compare an array of strings to another array of strings thus returning an array of non-matching strings

var master = ['1','2','3','4']
var versioned = ['1a','2','3b','4']
var errorLog = []
var count = 0;
//this for loop doesn't work :(
for(var i = 0; i < versioned.length - 1; ++i ){
    for(var j = 0; j < master.length -1; ++j){
        if(versioned[i] === master[j]){
            console.log('cleared');
        }
        if(count === master.length){
            errorLog.push(versioned[i]);
        }
    }
}

loop will return ['1a', '3b'];

I feel like filter() or map() or reduce() will do this but I'm unable to wrap my brain around this properly.

Armeen Moon
  • 18,061
  • 35
  • 120
  • 233
  • 2
    *Why, madame, if it so pleases the lady, would you please so carefully compare what I have in this basket, with what is in this very fine basket, and tell me, if you will, which is non-matching?* – Jared Farrish Oct 02 '15 at 23:05
  • See http://stackoverflow.com/a/14853974 and http://phpjs.org/functions/array_diff/ – Marat Tanalin Oct 02 '15 at 23:05
  • @MaratTanalin it's not returning a true false of the diff. It's returning an array of the non matching strings. – Armeen Moon Oct 02 '15 at 23:12
  • If you're only doing it one-sided like that, this should work: http://jsfiddle.net/8g1y2wdf/1 – Jared Farrish Oct 02 '15 at 23:16
  • The compiler or runtime does not care if something is "elegant". So what do you actually mean? Faster? Less code? Something else? This question is way too broad as it is. – JK. Oct 02 '15 at 23:30
  • @JK I really meant just to make it work. I did a huge forloop and it was pretty ugly with continues and breaks. Luckily filiter() made it pretty elegant. – Armeen Moon Oct 02 '15 at 23:36
  • @jk - [*Take your stinking paws off me you damn dirty code!*](http://stackoverflow.com/q/184618/451969) – Jared Farrish Oct 02 '15 at 23:40

1 Answers1

1
var master = ['1','2','3','4'];
var versioned = ['1a','2','3b','4'];

function diff(needle, haystack){
  return needle.filter(function(item){
    return !~haystack.indexOf(item); 
  });
}

console.log(diff(versioned, master)); //["1a", "3b"];

~ NOTing any number equals -(x + 1). so ~-1 becomes 0, which is the only falsy.

~master.indexOf(item) is the same as master.indexOf(item) !== -1

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98