简体   繁体   English

查找两个数组之间的对称差

[英]Finding the symmetric difference between two arrays

I need to find any differences between two arrays in the elements and push said elements onto a new array that is then returned in the end. 我需要找到元素中两个数组之间的任何差异,并将所述元素推到新数组中,然后最后返回。 I have pulled a function from this website through searching that has the intended purpose of counting the number of times an element occurs in an array and returning that. 我已经通过搜索从该网站提取了一个功能,该功能的目的是计算元素在数组中出现的次数并返回它。 First I have concatenated the two arrays together, then applied this function (modified it to fit my problem as well as I could). 首先,我将两个数组连接在一起,然后应用了此函数(对其进行了修改以尽可能地适应我的问题)。 I then tried to push the elements that were different (didn't occur twice) to the new array. 然后,我尝试将不同的元素(不会发生两次)推入新数组。 My code of course doesn't work and I am also new to Javascript, so please be easy on me. 我的代码当然行不通,并且对Javascript还是陌生的,所以请放心。

Below is some code of what I have tried, which doesn't pass any tests: 以下是我尝试过的代码,未通过任何测试:

function diffArray(arr1, arr2) {
  var newArr = [];

  let tempArr = arr1.concat(arr2);

  function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    if (countInArray(tempArr, tempArr[i]) < 2) {
      newArr.push(tempArr[i]);
    } 
}


  return newArr;
}

If you provide any code please try to break it down for me so that I can understand better and learn. 如果您提供任何代码,请尝试为我分解代码,以便我更好地理解和学习。

You could take a Set 你可以拿Set

The Set object lets you store unique values of any type, whether primitive values or object references. Set对象使您可以存储任何类型的唯一值,无论是原始值还是对象引用。

and return the difference from left and right side. 并从左侧和右侧返回差值。

 function getSymDifference(a, b) { return getDifference(a, b).concat(getDifference(b, a)); } function getDifference(a, b) { var setB = new Set(b); return a.filter(v => !setB.has(v)); } console.log(getSymDifference(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])); // ["pink wool"] console.log(getSymDifference([1, "calf", 3, "piglet"], [7, "filly"])); // [1, "calf", 3, "piglet", 7, "filly"] console.log(getSymDifference([], ["snuffleupagus", "cookie monster", "elmo"])); console.log(getSymDifference([1, 2, 3, 5], [1, 2, 3, 4, 5])); 

A classic approach by splicing the array to prevent using already visited or searched items to use again. 通过拼接数组以防止再次使用已访问或搜索的项目的经典方法。

 function getSymDifference(a, b) { var aa = a.slice(), bb = b.slice(), result = [], i, j; for (i = 0; i < aa.length; i++) { j = bb.indexOf(aa[i]); if (j === -1) { result.push(aa[i]); } else { bb.splice(j, 1); } } return result.concat(bb); } console.log(getSymDifference(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])); // ["pink wool"] console.log(getSymDifference([1, "calf", 3, "piglet"], [7, "filly"])); // [1, "calf", 3, "piglet", 7, "filly"] console.log(getSymDifference([], ["snuffleupagus", "cookie monster", "elmo"])); console.log(getSymDifference([1, 2, 3, 5], [1, 2, 3, 4, 5])); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

To achieve expected result, use below option by making few changes to your code 为了获得预期的结果,请使用以下选项,对您的代码进行少量更改

  1. Return count for countInArray (currently it returns undefined) 返回countInArray的计数 (当前返回未定义)

function countInArray(array, what) { var count = 0; for (var i = 0; i < array.length; i++) { if (array[i] === what) { count++; } } return count }

  1. Remove calling countInArray inside countInArray method 删除countInArray方法中的调用countInArray
  2. Run For Loop for tempArr to compare with other each value of tempArr 为tempArr运行循环以与tempArr的每个其他值进行比较

for (var j = 0; j < tempArr.length; j++) { if (countInArray(tempArr, tempArr[j]) < 2) { newArr.push(tempArr[j]); } }

Working code : 工作代码:

 function diffArray(arr1, arr2) { let tempArr = arr1.concat(arr2); let newArr = []; function countInArray(array, what) { var count = 0; for (var i = 0; i < array.length; i++) { if (array[i] === what) { count++; } } return count } for (var j = 0; j < tempArr.length; j++) { if (countInArray(tempArr, tempArr[j]) < 2) { newArr.push(tempArr[j]); } } return newArr; } let arr1 = ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"] let arr2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"] console.log(diffArray(arr1, arr2)) let arr3 = [1, "calf", 3, "piglet"] let arr4 = [7, "filly"] console.log(diffArray(arr3, arr4)) 

codepen - https://codepen.io/nagasai/pen/OYNdZX?editors=1010 codepen- https: //codepen.io/nagasai/pen/OYNdZX ? editors = 1010

reverse the second array and probably that should ease your task 反转第二个数组,可能可以简化您的任务

Array.Reverse method: http://www.w3schools.com/jsref/jsref_reverse.asp Array.Reverse方法: http : //www.w3schools.com/jsref/jsref_reverse.asp

The most elegant solution I could find is stated using ES7 apparently. 我可以找到的最优雅的解决方案显然是使用ES7。 I'll post it below, but if someone could help me figure out how to make my initial code work, that would be appreciated. 我将其张贴在下面,但是如果有人可以帮助我弄清楚如何使我的初始代码正常工作,将不胜感激。

function diffArray(arr1, arr2) {

let difference = arr1
                 .filter(x => !arr2.includes(x))
                 .concat(arr2.filter(x => !arr1.includes(x)));


  return difference;
}

Basically this filters the first array based on what the second doesn't have and concatenates on the filtered second array based on what doesn't occur in the first. 基本上,这会根据第二个数组没有的内容来过滤第一个数组,并根据第一个数组中没有的内容在已过滤的第二个数组上串联。 So it gets both sides, not just one, hence 'symmetric'. 因此,它得到了双方,而不仅是双方,因此是“对称的”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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