0

How can the function below be adapated to search through 2 dimensional arrays? I can't figure it out. I need the example below to result in '["sainsburys"]'.

Thanks

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return !(a[0].indexOf(i[0]) > -1);});
};

var oldSupermarkets = [["asda"], ["tesco"], ["sainsburys"]];
var newSupermarkets = [["asda"], ["tesco"]];
jskidd3
  • 4,609
  • 15
  • 63
  • 127
  • possible duplicate of [Comparing two arrays in Javascript](http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript) – Barmar Jul 24 '13 at 10:31
  • @Barmar No it's not, these arrays are two dimensional and I'm pretty sure the answers are going to be quite different. – jskidd3 Jul 24 '13 at 10:32
  • 1
    Why is it a 2d-array - could the strings not just be strings, and not "wrapped" as an array..? – Thor Jacobsen Jul 24 '13 at 10:32
  • @ThorJacobsen Well yes that would be amazing, but sadly that's not what I've been asked to do. :P – jskidd3 Jul 24 '13 at 10:33
  • @JoelKidd His filter function needs to compare the sub-arrays, so he can use that code to do it. – Barmar Jul 24 '13 at 10:38
  • @Barmar Sure but they're just comparing and returning true or false, I need to actually get the value that's missing. – jskidd3 Jul 24 '13 at 10:40
  • That's what `filter` does. It returns all the elements that the function returns `true` for. – Barmar Jul 24 '13 at 10:41

1 Answers1

1

This does what you want:

Array.prototype.diff = function(a) {
    var b = a.map(function(x) { return x[0]; });
    return this.filter(function(x) { return b.indexOf(x[0]) == -1; });
};

I could give you a more accurate answer if you'd tell us what those twodimensional arrays respresent - what it would mean if the inner arrays had more than one item. Currently they look just unnecessary, and you just could flatten them and use the one-dimensional diff function.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks very much Bergi. I can tell you that the each sub-array contains more than 10 items, but the index of the item im searching is number 3, so I'd just swap x[0] to x[3], right? Thanks again. – jskidd3 Jul 24 '13 at 16:49
  • Can you give me an example of how I'd be able to use this function with the two arrays I gave in the question? How you'd call it I mean. Thanks – jskidd3 Jul 24 '13 at 16:51
  • If you want to compare the subarrays by their fourth item, then just change both `0`s to `3`, yes. To call it, it's just `oldSupermarkets.diff(newSupermarkets)` – Bergi Jul 24 '13 at 17:10