将字符串数组与另一个字符串数组进行比较的优雅方法

时间:2015-10-02 23:02:26

标签: javascript arrays loops

问题:如何优雅地将字符串数组与另一个字符串数组进行比较,从而返回一组不匹配的字符串

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]);
        }
    }
}

循环将返回[&#39; 1a&#39;,&#39; 3b&#39;];

我觉得filter()map()reduce()会做到这一点,但我无法正确地围绕这一点。

1 个答案:

答案 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

相同