猿问

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

我需要找到元素中两个数组之间的任何差异,并将所述元素推到新数组中,然后最后返回该数组。我通过搜索从该网站提取了一个功能,该功能的目的是计算元素在数组中出现的次数并返回该次数。首先,我将两个数组连接在一起,然后应用了此函数(对其进行了修改以尽可能地适应我的问题)。然后,我尝试将不同的元素(不会发生两次)推到新数组中。我的代码当然行不通,并且对Javascript还是陌生的,所以请放轻松。


以下是我尝试过的代码,未通过任何测试:


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;

}

如果您提供任何代码,请尝试为我分解代码,以便我更好地理解和学习。


九州编程
浏览 198回答 3
3回答

沧海一幻觉

你可以拿一个 Set该Set对象允许您存储任何类型的唯一值,无论是原始值或对象引用。并从左侧和右侧返回差值。function getSymDifference(a, b) {&nbsp; &nbsp; return getDifference(a, b).concat(getDifference(b, a));}function getDifference(a, b) {&nbsp; &nbsp; var setB = new Set(b);&nbsp; &nbsp; 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]));通过拼接数组以防止再次使用已访问或搜索的项目的经典方法。function getSymDifference(a, b) {&nbsp; &nbsp; var aa = a.slice(),&nbsp; &nbsp; &nbsp; &nbsp; bb = b.slice(),&nbsp; &nbsp; &nbsp; &nbsp; result = [],&nbsp; &nbsp; &nbsp; &nbsp; i, j;&nbsp; &nbsp; for (i = 0; i < aa.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; j = bb.indexOf(aa[i]);&nbsp; &nbsp; &nbsp; &nbsp; if (j === -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push(aa[i]);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bb.splice(j, 1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; 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; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答