JavaScript基础算法——Diff Two Arrays

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/88828939

要求:

比较两个数组,然后返回一个新数组,该数组的元素为两个给定数组中所有独有的数组元素。换言之,返回两个数组的差异。

样本:

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]) 应该返回一个数组。

["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] 应该返回 ["pink wool"]

["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] 应该返回 ["diorite", "pink wool"]

["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] 应该返回 []

[1, 2, 3, 5], [1, 2, 3, 4, 5] 应该返回 [4]

[1, "calf", 3, "piglet"], [1, "calf", 3, 4] 应该返回 ["piglet", 4]

[], ["snuffleupagus", "cookie monster", "elmo"] 应该返回 ["snuffleupagus", "cookie monster", "elmo"]

[1, "calf", 3, "piglet"], [7, "filly"] 应该返回 [1, "calf", 3, "piglet", 7, "filly"]

解法:

function diff(arr1, arr2) {
  var newArr=[];
  var checked = [];
  var found = false;
  for(var j=0;j<arr1.length;j++){
    for(var i=0;i<arr2.length&&!found;i++){
      //如果已经检查过是相同就跳过
      if(!checked.includes(i)){
        //如果相同就记住下次不查
        if(arr2[i]===arr1[j]){
          checked.push(arr2.indexOf(arr2[i]));
          found = true;//已经找到相同
        }
      }
    }
    if(!found){
      newArr.push(arr1[j]);
    }else{
      found=false;
    }
  }
  //检查arr1中有arr2中没有的
  for(var k=0;k<arr2.length;k++){
      if(!checked.includes(k)){
          newArr.push(arr2[k]);
      }
  }
  return newArr;
}

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

猜你喜欢

转载自blog.csdn.net/funkstill/article/details/88828939