Compare two Arrays and replace Duplicates with values from a third array

前端 未结 7 1908
不思量自难忘°
不思量自难忘° 2021-01-22 11:54
var array1 = [\'a\',\'b\',\'c\',\'d\'];
var array2 = [\'a\',\'v\',\'n\',\'d\',\'i\',\'f\'];

var array3 = [\'1\',\'2\',\'3\',\'4\',\'5\',\'6\'];

Just s

7条回答
  •  走了就别回头了
    2021-01-22 12:55

    You could use a hash table and check against. If the string is not included in the hash table, a replacement value is set for this element.

    var array1 = ['a','b','c','d'],
        array2 = ['d','v','n','a','i','f'],
        array3 = ['1','2','3','4','5','6'],
        hash = Object.create(null);
    
    array1.forEach(function (a) {
        hash[a] = true;
    });
    
    array2.forEach(function (a, i, aa) {
        if (hash[a]) {
            aa[i] = array3[i];
        }
    });
    
    console.log(array2);

    ES6 with Set

    var array1 = ['a','b','c','d'],
        array2 = ['d','v','n','a','i','f'],
        array3 = ['1','2','3','4','5','6'];
    
    array2.forEach((hash => (a, i, aa) => {
        if (hash.has(a)) {
            aa[i] = array3[i];
        }
    })(new Set(array1)));
    
    console.log(array2);

提交回复
热议问题