0

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?

3 Answers3

0

What you're looking for is called array intersection. Calculate it, then take the length of the resulting array.

Simplest code for array intersection in javascript

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

http://jsfiddle.net/Gsg4h/

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