1.任务及要求
Diff Two Arrays
比较两个数组,然后返回一个新数组,该数组的元素为两个给定数组中所有独有的数组元素。换言之,返回两个数组的差异。
如果你被难住了,记得使用 Read-Search-Ask尝试与他人结伴编程、编写你自己的代码。
这是一些对你有帮助的资源:
测试数据:
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"]
。
2.我的解法
function diff(arr1, arr2) { // First time; var newArr = []; newArr = arr1.filter(function(isIn){ if(arr2.indexOf(isIn)==-1){ return isIn; } }).concat(arr2.filter(function(isIn){ if(arr1.indexOf(isIn)==-1){ return isIn; } })); // Same, same; but different. return newArr; //或者-or /* return arr1.filter(function(isIn){ return arr2.indexOf(isIn)==-1; }).concat(arr2.filter(function(isIn){ return arr1.indexOf(isIn)==-1; })); */ } diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);