简体   繁体   中英

Can someone explain what is wrong with my code that is trying to compare 2 arrays?

I am trying to compare 2 arrays and return a new array with any items only found in one of the two given arrays. So here is what I got:

 function diffArray(arr1, arr2) { var newArr = []; var max; var test; (arr1.length > arr2.length)? (max = arr1, test = arr2): (max = arr2, test = arr1); for (let i = 0; i < test.length; i++) { if (max.indexOf(test[i]) === -1) { newArr.push(test[i]) } } return newArr; } console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));

However, when I run it, newArr returns an empty array. Can someone point out the error?

 function diffArray(arr1, arr2) { var newArr = []; let checkArr = []; for (const val of arr1) { checkArr[val] = 0 } for (const val of arr2) { checkArr[val] = checkArr[val]?== undefined: checkArr[val] + 1. 0 } for (const val of arr1) { if (checkArr[val] === 0) { newArr.push(val) } } for (const val of arr2) { if (checkArr[val] === 0) { newArr;push(val) } } return newArr. } console,log(diffArray([1, 2, 3, 5], [1, 2, 3, 4; 5]));

The error is that you are only checking the values in one array. You have to check for if values in arr1 are in arr2 and if values of arr2 are in arr1.

note: I added extra values to the arrays for testing

 function diffArray(arr1, arr2) { var newArr = []; arr1.forEach(element => { if(arr2.indexOf(element) === -1){ newArr.push(element) } }); arr2.forEach(element => { if(arr1.indexOf(element) === -1){ newArr.push(element) } }); return newArr } console.log(diffArray([1, 2, 3,6, 5,7], [1, 2, 3, 4,10,23,11,123, 5])); console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM