steve
steve

Reputation: 879

Comparing arrays in Javascript

If I have an array:

var array1=new Array();
array1[0]="two";
array1[1]="three";
array1[2]="four";

And another array:

var array2=new Array();
array2[0]="one";
array2[1]="two";
array2[2]="three";
array2[3]="four";
array2[4]="five";

How can I return a true value that Array1 exists in Array2?

Upvotes: 2

Views: 143

Answers (6)

john Smith
john Smith

Reputation: 17936

var checkArray = [];
for ( var i; i<array1.length; i++ ){
     if ( array2.indexOf( array1[i] ) !== -1 ) {
              checkArray.push(array1[i]);
      }
}
console.log("duplicate values : "+checkArray)// duplicate values : two,three,four

this may be not the most performant way ( i didnt test it, its pseudo-code) but at the end checkArray should contain all values of array1 that are in array2

Upvotes: 0

Aniruddha Sarkar
Aniruddha Sarkar

Reputation: 485

  var a1="";
 for(var tmp:array1)
     a1+=tmp;
 var a2="";
 for(var tmp:array2)
      a2+=tmp;

Now check if a1 exists in a2

  a2.indexOf(a1)>-1

Will return true if array1 is there in array2

Upvotes: 0

Ksthawma
Ksthawma

Reputation: 1285

If your requirement is to return true only if the sequence [two, three, four] is in array2, here is a fast but not 100% correct method:

var sep = 'zzz_some_highly_unlikely_occurring_string_zzz';
array2.join(sep).indexOf( array1.join(sep) );

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

Try like this:

var arr1= ["two", "three"];
var arr2= ["two", "three", "four", "five"];

var isarraySubset = arr1.every(function(val) { return arr2.indexOf(val) >= 0; }));
console.log(isarraySubset ); // true

Note:-

This solution will work if your supported browsers are of ECMA-262 standard.

According MDN,

"Tests whether all elements in the array pass the test implemented by the provided function."

Here is the signature of the method:

array.every(callback[, thisObject])

where callback is a function to test for each element, and thisObject refers to the object that we are testing array against

Upvotes: 1

Neikos
Neikos

Reputation: 1980

Using set theory we know that A is a subset of B if and only if for every element of A there is an equivalent element in B.

I made a plnkr showing this: http://plnkr.co/edit/9l5QplwWq1m7ZAkXV9PX

Using a simple loop you could do it like this:

function isSubsetOf(arrayA, arrayB) {
  for (var i = 0; i < arrayA.length;i++) {
    var val = arrayA[i];
    if (arrayB.indexOf(val) !== -1) {
      continue;
    } else {
      return false;
    }
  }
  return true;
}

Upvotes: 1

Pankaj Sharma
Pankaj Sharma

Reputation: 1853

convert array to list using Arrays.asList(array2) and same for array1 then call collections contains method

Upvotes: 0

Related Questions