问题:如何优雅地将字符串数组与另一个字符串数组进行比较,从而返回一组不匹配的字符串
var master = ['1','2','3','4']
var versioned = ['1a','2','3b','4']
var errorLog = []
var count = 0;
//this for loop doesn't work :(
for(var i = 0; i < versioned.length - 1; ++i ){
for(var j = 0; j < master.length -1; ++j){
if(versioned[i] === master[j]){
console.log('cleared');
}
if(count === master.length){
errorLog.push(versioned[i]);
}
}
}
我觉得filter()
或map()
或reduce()
会做到这一点,但我无法正确地围绕这一点。
答案 0 :(得分:1)
var master = ['1','2','3','4'];
var versioned = ['1a','2','3b','4'];
function diff(needle, haystack){
return needle.filter(function(item){
return !~haystack.indexOf(item);
});
}
console.log(diff(versioned, master)); //["1a", "3b"];
~
注意任何数字等于 - (x + 1)。所以〜-1变为0,这是唯一的假。
~master.indexOf(item)
与master.indexOf(item) !== -1