差分数组,结果为 1 或未定义

Difference of array, result is 1 or undefined

Array a = [1,2,3,4,5,5]

Array b = [1,2,3,5]

c = a - b

应该 return c = [4] (5 重复了两次,但我不希望它出现在输出中) 现在这是我的代码:

function arrayDiff(a, b) {
  var array = [];
  var diff = [];
  for (var i = 0; i<a.length; i++) {
    array[a[i]] = true;
  }

  for (var i = 0; i<b.length; i++) {
    if (array[b[i]]) {
      delete array[b[i]];
    }
    else {
      array[b[i]] = true;
    }

    for (var k in array) {
      return diff.push(k);
    }

  }

}
Test.describe("Sample tests", function() {
  Test.it("Should pass Sample tests", function() {
    Test.assertDeepEquals(arrayDiff([], [4,5]), [], "a was [], b was [4,5]");
    Test.assertDeepEquals(arrayDiff([3,4], [3]), [4], "a was [3,4], b was [3]");
    Test.assertDeepEquals(arrayDiff([1,8,2], []), [1,8,2], "a was [1,8,2], b was []");
  });
}); 

但它 return 很奇怪。你能解释一下为什么它 returns 1 吗?我该如何解决?这是 console.log 输出:


a was [], b was [4,5] - Expected: [], instead got: 1
a was [3,4], b was [3] - Expected: [4], instead got: 1
a was [1,8,2], b was [] - Expected: [1, 8, 2], instead got: undefined


Unhandled rejection TestError: a was [], b was [4,5] - Expected: [], instead got: 1

你能帮我解决一下吗?

你的代码看起来不错。它可能需要一些修改以使其简单。

function arrayDiff(a, b) {
  return a.filter((aItem) => b.indexOf(aItem) === -1);
}

您可以使用 Set 并过滤数组。

function arrayDiff(a, b) {
    const setB = new Set(b);
    return a.filter(v => !setB.has(v));
}

console.log(arrayDiff([1, 2, 3, 4, 5, 5], [1, 2, 3, 5]));

你的代码有几个问题

  1. 嵌套在第二个 for 循环内的第三个 for 循环不应嵌套在第二个循环内。

  2. .push() 方法在数组中添加一个新项,returns 添加新项后数组的长度。您需要 return diff 数组,而不是 returning 推送函数的 return 值。

这是固定代码

const a = [1,2,3,4,5,5];
const b = [1,2,3,5];

function arrayDiff(a, b) {
  var array = [];
  var diff = [];
  for (var i = 0; i<a.length; i++) {
    array[a[i]] = true;
  }
  
  for (var i = 0; i<b.length; i++) {
    if (array[b[i]]) {
      delete array[b[i]];
    }
    else {
      array[b[i]] = true;
    }
  }
    
  for (var k in array) {
      diff.push(Number(k));
  }
  
  return diff;
  
}

console.log(arrayDiff(a, b));

编辑

根据您的评论,如果 a = []b = [1, 2] 则输出应为 [],对于 a = [1, 8, 2]b = [],输出应为 [1, 8 ,2]

这对于您的代码是不可能的,因为您是根据数组索引和布尔值发现差异的。

您可以通过过滤数组 a 并检查数组 a 中的当前元素是否存在于数组 b 中来获得所需的输出。

let a = [1, 8 ,2];
let b = [];

function arrayDiff(a, b) {
  return a.filter(n => !b.includes(n));
}

console.log(arrayDiff(a, b));