0

Is there a way to compare 2 arrays and return a new array indicating which values matched?

For example

a = ['Africa', 'America', 'Europe']
b = ['Africa', 'Asia', 'Europe']

// need
// c = [true, false, true]

EDIT: So far I have

function mask(arr1, arr2) {
  var arr = [];
  for (var i = 0; i < arr1.length; i++) { 
    arr.push(arr1[i] === arr2[i]);
  }
  return arr;
}
sizeight
  • 719
  • 1
  • 8
  • 19

2 Answers2

3

just loop through the array. for Example:

var a = ['Africa', 'America', 'Europe'];
var b = ['Africa', 'Asia', 'Europe'];

var index = 0;
var c = [];
while(a.length > index){
  c.push(a[index] === b[index]);
  index++
}
Tom
  • 195
  • 9
  • Thanks, I answered my own question above, very similar to your solution. Any idea which loop would be the most performant, 'while' or 'for'? – sizeight Jul 08 '15 at 07:57
  • 1
    In theory while is more performant than for, but it is very insignificant. There used to be a site called [link]http://jsperf.com which had comparisons like that, but it is currently offline. – Tom Jul 08 '15 at 08:07
  • one of the fine answer which full fill the complete requirement and manage the complexity too – dom Jul 27 '15 at 04:39
-1

you can use the following code to compare two array in js

<script type="text/javascript">

function checkForArray(){

var arr1 = [1,5,9,10,12];
var arr2 = [2,3,4,5,9];
var arr3 = [];


for(var i=0;i<arr1.length;i++){

   for(var j=0;j<arr2.length;j++){

     if(arr1[i] == arr2[j]){
         arr3.push(arr1[i]);
     }

  }
}

alert(arr3);
}
</script>
dom
  • 1,086
  • 11
  • 24