[英]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.我正在尝试比较 2 个 arrays 并返回一个新数组,其中包含仅在两个给定 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.但是,当我运行它时, newArr 返回一个空数组。 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.
您必须检查 arr1 中的值是否在 arr2 中,以及 arr2 的值是否在 arr1 中。
note: I added extra values to the arrays for testing注意:我在 arrays 中添加了额外的值进行测试
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]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.