So, I am coding an text bot with Javascript. I have coded c# before, but this is my first Javascript program. So my question is, how do you get the amount of same strings between two arrays? So, let's say we have an array, which contains values " how", "are" and "you". Another array has values "how","is","it" and "going". So, how can I create a function which returns 1 from those arrays?
Asked
Active
Viewed 53 times
0
-
What's the basis for coming up with the `1`? Number of same words? – Joseph Nov 11 '13 at 14:40
-
It's the number of same values in the arrays – user2979511 Nov 11 '13 at 14:41
-
Thanks, I think I can do it from here on :) – user2979511 Nov 11 '13 at 14:50
3 Answers
0
What you're looking for is called array intersection. Calculate it, then take the length of the resulting array.

Community
- 1
- 1

Alex Weinstein
- 9,823
- 9
- 42
- 59
0
var count = 0;
arr1.forEach(function (elem) {
if (arr2.indexOf(elem) !== -1) {
count++;
}
});

Explosion Pills
- 188,624
- 52
- 326
- 405
0
This is an adapted underscore.intersect(). Should work as long as all the native Array methods: indexOf
, every
, and filter
are polyfilled
var intersect = function (array) {
var rest = array.slice.call(arguments, 1);
return array.filter(function(item) {
return rest.every(function(other) {
return other.indexOf(item) >= 0;
});
});
}
Can be called like:
var dups = intersect([1,2,3],[1,2],[5,8,2]);//[2]
var numofdups = dups.length;

megawac
- 10,953
- 5
- 40
- 61