1

I have 2 string arrays:

var X = ['A', 'B', 'C'],
    Y = ['B', 'C', 'D'];

I need to create an array Z, such that Z = A ∩ B

Z = ['B', 'C'];

Z contains the strings that are both in X and Y.

I've done it this way:

A.forEach(function(i) {
  B.forEach(function(j) {
    if (i === j) Z.push(i);
  });
});

Any suggestions / comments?

martynas
  • 12,120
  • 3
  • 55
  • 60
  • http://stackoverflow.com/questions/12433604/how-can-i-find-matching-values-in-two-arrays – Amit Apr 15 '14 at 09:11
  • There is no magic to this, you would have to iterate through elements, if you are using any helper function then that function internally would be doing loop as well. – Amit Apr 15 '14 at 09:12

1 Answers1

2

I'd better use filter method:

['A', 'B', 'C'].filter(function(c) {
    return ['B', 'C', 'D'].indexOf(c) > -1;
});
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Right, using `.indexOf()` was my initial approach. The problem is that if array has 2 similar words like "INTERNATIONAL and "NATIONAL" - both of them appear as matching :) – martynas Apr 15 '14 at 09:13
  • 2
    It shouldn't, as you're mixing two different `indexOf` methods: [for arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [for strings](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). – VisioN Apr 15 '14 at 09:15
  • Works like a charm. What are the advantages of using `filter` instead of my solution? – martynas Apr 15 '14 at 09:18
  • @martynas I see no particular advantages... both should be rather fast. Maybe `filter` approach is slightly shorter and clearer. – VisioN Apr 15 '14 at 09:20
  • Hmm... not sure how filter works but my method might have redundant operations. – martynas Apr 15 '14 at 09:23
  • @martynas It creates a new array with elements that match the condition given in the callback. In your case you use two callbacks for `forEach`, while here there is only one, as another is implicitly implemented inside `indexOf` method. – VisioN Apr 15 '14 at 09:25