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

前端 未结 7 1898
不思量自难忘°
不思量自难忘° 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:53

    Use Array.prototype.reduce to check the duplicates and create a new array - see demo below:

    var array1 = ['a','b','c','d'];
    var array2 = ['a','v','n','d','i','f'];
    
    var array3 = ['1','2','3','4','5','6'];
    
    var result = array2.reduce(function(p,c,i){
      if(array1.indexOf(c) !== -1) {
         p.push(array3[i]);
      } else {
         p.push(c);
      }
      return p;
    },[]);
    
    console.log(result);

提交回复
热议问题