-2

I want to compare two arrays and return a new array with any items only found in one of the two given arrays, but not both

This is my code :

function diffArray(arr1, arr2) {
    var newArr = []; 
    for(var i =0; i <arr1.length ; i++){
        
            if(arr2.indexOf(arr1[i]) < 0){
                newArr.push(arr1[i]);
              }
            }
    for(var j =0; j <arr2.length ; j++){
            
                if(newArr.includes(arr2[i]) !== true){
                    if(arr1.indexOf(arr2[i])<0){
                    newArr.push(arr2[i])
                  }
                }             
            }
  
    return newArr;
  }
  

its not working right. newArr after first for loop is empty , i cant get where i am wrong .. thank you in advance for any idea

Ashish
  • 623
  • 4
  • 10
Nasim
  • 161
  • 1
  • 3
  • 12

1 Answers1

1

This works embed it into function

let ad=[1,2,3,4,8,9];
let b=[2,7,8,1];
   
let k=ad.reduce((o,a)=>{
  if(b.indexOf(a) > -1)
  {
    o.push(a);
  }
  return o;

},[])


console.log(k);
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
  • thank you so much , but i wanna know where am i wrong in my code – Nasim Jan 03 '19 at 07:39
  • I guess the problem is with `includes` function ,you should check its use -https://www.w3schools.com/jsref/jsref_includes.asp .Anyway pls accept the answer if it worked for you .Thanks – Shubham Dixit Jan 03 '19 at 08:34