Uzma Khan Uzma Khan - 26 days ago 9
Javascript Question

Compare two arrays and return a new array with any items only found in one of the original arrays

["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"]
,

["diorite", "andesite", "grass", "dirt", "dead shrub"]

should return
["pink wool"]
.

Because "pink wool is not present in first array i.e arr1.But it is returning an empty array.This code is working fine with numbers only Array.But when array includes only string or strings with numbers the code does not work.

function diff(arr1, arr2) {

var newArray=arr2.concat(arr1); //first joininng both arrays inn one and storing it in newArray

var newestArray=[];

for(var i=0;i<newArray.length;i++){ //NOW COMPARING EACH ELEMENT OF newArray WITH ARR1 AD ARR2 AND PUSHING NOT SAME VALUES TO newestArray

if(arr1.indexOf(newArray[i])==-1) {
newestArray.push(newArray[i]);

if(arr2.indexOf(newArray[i])==-1){
newestArray.push(newArray[i]);
}
}
}

return newestArray.filter(Boolean); //It is returning an empty arrray but it should return "pink wool"

}

diff(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

Answer

Guys thanks a lot for your help but when a person is asking a question like mine,we are not asking for a brand new solution for our problem.That will be clear cut copying and what will I learn from that? What about all the time I put to solve my problem.My solution can be corrected,I need to solve that thing,so that I don't repeat such mistake and can learn where I was wrong.

I found out there was a very silly mistake of braces only and that solved my whole problem.

    function diff(arr1, arr2) {

  var newArray=arr2.concat(arr1);  //first joininng both arrays inn one and storing it in newArray 

 var newestArray=[];

                   for(var i=0;i<newArray.length;i++){  //NOW COMPARING EACH ELEMENT OF  newArray  WITH ARR1 AD ARR2 AND PUSHING NOT SAME VALUES TO newestArray

               if(arr1.indexOf(newArray[i])===-1) {
                 newestArray.push(newArray[i]);}  //Solution to my problem,I put this braces after the next if,becuase of that next if was not running. 

                if(arr2.indexOf(newArray[i])===-1){
                 newestArray.push(newArray[i]);
                }

             }

  return newestArray;   //It is returning an empty arrray but it should return "pink wool"

}

diff(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);
Comments