在数组测试中查找对称差异失败

时间:2017-03-28 20:42:29

标签: javascript

sym([1,1,2,5],[2,2,3,5],[3,4,5,5])应该返回[1,4,5] 预期回报如上所示。但我找不到为什么它没有通过这个测试。下面的代码需要什么样的修复?

function sym(args) {
	//debugger;
	var arr=Array.from(arguments);
  var resArr=[];
 
 	arr.forEach(function(arrVal){
        var c=0;

      arrVal.forEach(function(val,index){
      console.log("arrVal",arrVal,"index",index,"val",val,"|",arrVal.slice(index+1-c));
        if(index<arrVal.length-1 && arrVal.slice(index+1-c).indexOf(val)!==-1){
        console.log("here");
        	
          arrVal.splice(index-c,1);
          c++;
        }
                    console.log("arrVal",arrVal,"index",index,"|",arrVal);

      });

      resArr.push(arrVal);
    });
		console.log(resArr);
  	
  resArr=resArr.reduce(function(acc,curr){
  	return acc.concat(curr.filter(function(val){
    	var notContains=acc.indexOf(val)==-1;
    	if(!notContains)
      	acc.splice(acc.indexOf(val),1);
    	return notContains;
    }));
  },[]);
    
 
 console.log(resArr);
  return resArr;
}

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

2 个答案:

答案 0 :(得分:1)

您可以使用更简洁的版本来过滤重复项。

&#13;
&#13;
function sym(array) {
    return array.reduce(function (r, a) {
        return r.concat(a.filter(function (a, i, aa) {
            return i === aa.indexOf(a);
        })).filter(function (a, i, aa) {
            return aa.indexOf(a) === aa.lastIndexOf(a);
        });
    }, []);
}

console.log(sym([[1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]])); // [1, 4, 5]
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用set for a PE by the linkerSets应该足够了。扩展他们的原型并从有意义的方法中获益(unionintersectiondifference取自MDN):

Set.prototype.union = function(setB) {
    var union = new Set(this);
    for (var elem of setB) {
        union.add(elem);
    }
    return union;
}

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}

Set.prototype.difference = function(setB) {
    var difference = new Set(this);
    for (var elem of setB) {
        difference.delete(elem);
    }
    return difference;
}

Set.prototype.symmetricDifference = function(setB) {
    return this.union(setB).difference(this.intersection(setB));
}


var set1 = new Set([1, 1, 2, 5]);
var set2 = new Set([2, 2, 3, 5]);
var set3 = new Set([3, 4, 5, 5]);
var result = set1.symmetricDifference(set2).symmetricDifference(set3);
console.log(result); // as Set
console.log([...result]); // as Array