2

I have below arrow and I want to get common value from all four array. I have try below code and it's working but not the correct way I want. Instead of coming [2, 3] in new array it showing other value which are common at least in two or three array.

Fiddle Demo

My Code

var a = [11, 2, 3, 4],
    b = [2,  6, 3, 5],
    c = [4, 2, 20, 3],
    d = [34, 2, 21, 5, 3],
    result = [],
    common = [];

function findCommon () {    
    for(var i = 0; i < arguments.length; i++){
        var garr = arguments[i];
        result = result.concat(arguments[i]);
    };
}
findCommon(a,b,c,d);

var sorted_arr = result.sort();

for(var i = 0; i< result.length-1; i++){

    if(result[i+1] == sorted_arr[i]){
        common.push(result[i]);
    }
};

alert(common); //[2, 2, 2, 3, 3, 4, 5]
Rakesh Kumar
  • 2,705
  • 1
  • 19
  • 33

5 Answers5

1

Try this:

function findCommon()
{
    var common=[];
    for(i=0; i<a.length; i++)
    {
       if(b.indexOf(i) != -1 && c.indexOf(i) != -1 && d.indexOf(i) != -1) 
       {
          common.push(i);
       }
    }
    return common;
}

This will return array of common values between all four arrays. Here is the working fiddle.

hamed
  • 7,939
  • 15
  • 60
  • 114
  • if we have two data common in all four array then this code will not work – Rakesh Kumar Apr 21 '15 at 09:54
  • What happens when a value appears in only three arrays and it's the most common? What happens when the common doesn't appear in a? – Amir Popovich Apr 21 '15 at 10:01
  • He wants to get common value from **all four arrays**. – hamed Apr 21 '15 at 10:03
  • Try with these values : a = [11, 82, 3, 4], b = [62, 6, 3, 5], c = [4, 2, 20, 3], d = [34, 2, 21, 5]; It will fail – Puneet Apr 21 '15 at 10:08
  • There is not any common value between **all** these four arrays! – hamed Apr 21 '15 at 10:10
  • First line of the question: **I want to get common value from _all_ four array** – hamed Apr 21 '15 at 10:12
  • Note that while the question says _4_ arrays, the OP uses `arguments` in his function which might lead us to think that _4_ is just an example in this case and he/she might want more than 4 arrays to deal with in the future. Your code isn't future-proof. – Andy Apr 21 '15 at 10:52
1

You could use arrays as the values of an object, and use the numbers as the keys. It makes it easy to count the numbers then. Note, this code is also future proof, so that if you want fewer or more arrays to test, this will let you. It also de-dupes the individual arrays, so numbers within each are only counted once to prevent errors.

function findCommon() {
    var obj = {};
    var out = [];
    var result = [];

    // convert arguments to a proper array
    var args = [].slice.call(arguments);
    var len = args.length;
    for (var i = 0, l = len; i < l; i++) {

      // grab a de-duped array and and concatenate it
      // http://stackoverflow.com/a/9229821/1377002
      var unique = args[i].filter(function(item, pos) {
        return args[i].indexOf(item) == pos;
      });
      result = result.concat(unique);
    }
    for (var i = 0, l = result.length; i < l; i++) {
        var el = result[i];

        // if the object key doesn't exist, create an array
        // as the value; add the number to the array
        if (!obj[el]) obj[el] = [];
        obj[el].push(el);
    }
    for (var p in obj) {

     // if the array length equals the original length of
     // the number of arrays added to the function
     // add it to the output array, as an integer
     if (obj[p].length === len) out.push(+p);
    }
    return out;
}

findCommon(a, b, c, d); // [2]

In addition, this will find all multiple keys, so if you replace the 5 in d as 3, the result will be [2, 3].

DEMO which uses 4 arrays, multiple hits

DEMO which uses 5 arrays

Andy
  • 61,948
  • 13
  • 68
  • 95
  • code get break if I put my array like `var a = [11, 22, 3, 4], b = [22, 6, 3, 5], c = [4, 22, 22, 3], d = [34, 2, 21, 3];` in all arrays now i put 22 two times in third array and not in fourth array. – Rakesh Kumar Apr 21 '15 at 11:39
  • @RakeshKumar, try this: http://jsfiddle.net/6zo91dk9/2/. I've updated the answer too. – Andy Apr 21 '15 at 11:55
  • @RakeshKumar, I had to go back to your version of concatenation to make this work. – Andy Apr 21 '15 at 11:58
  • 1
    Great Man you rocks! Thanks for the answer. – Rakesh Kumar Apr 21 '15 at 14:21
0

You cna use indexOf to resolve that:

array.indexOf(element) >=0 // it means that element is in array

or

array.indexOf(element) != -1

When you would be using jQuery, thre is a shorter version:

$.inArray(value, array)

More fancy way, would be to use filter (Filter):

function hasElement(element, index, array) {
  return element.indexOf(i) >= 0;
}
filtered = [a,b,c,d].filter(hasElement);
filtered.length  === 4
Beri
  • 11,470
  • 4
  • 35
  • 57
0

Assuming you want something generic for X arrays and we are talking about integers this sounds to me like some bucket business.

var a = [11, 2, 3, 4],
    b = [2,  6, 3, 5],
    c = [4, 2, 20, 3],
    d = [34, 2, 21, 5];

function findCommon()
{
    var bucket = [];
    var maxVal = 0;
    var minVal = 0;

        for(var i = 0; i < arguments.length; i++)
        {
            for(var j = 0 ; j < arguments[i].length ; j++)
            {
                var val = arguments[i][j];
                bucket[val] = bucket[val] + 1 || 1;
                if(val > maxVal)
                {
                    maxVal = val;
                }
                else if(val < minVal)
                {
                    minVal = val;
                }
            }
        }

    var retVal = 0;
    var maxTimes = 0;
    for(var i = minVal ; i <= maxVal ; i++)
    {
        var val = bucket[i];
        if(val > maxTimes)
        {
            maxTimes = val;
            retVal = i;
        }
    }

    return retVal;
}

console.log(findCommon(a,b,c,d));

JSFIDDLE.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
0

This Try,

will find the common number with number of times it repeated.

var a = [11, 2, 3, 4],
    b = [2,  6, 3, 5],
    c = [4, 2, 20, 3],
    d = [34, 2, 21, 5],
    result = [],
    common = [];

var all = a.concat(b).concat(c).concat(d);


var commonNum=0;
var largestCounter=0
for(var i = 0; i< all.length-1; i++){
    var counter=0;
    if(a.indexOf(all[i])>-1) counter+=1;
    if(b.indexOf(all[i])>-1) counter+=1;
    if(c.indexOf(all[i])>-1) counter+=1;
    if(d.indexOf(all[i])>-1) counter+=1;
     
  if(counter>largestCounter)
    {largestCounter = counter;
     commonNum = all[i];
     }
    
  
   
};

alert(commonNum+" with count " + largestCounter);
Puneet
  • 2,051
  • 9
  • 17