Compare two Arrays and replace Duplicates with val

2020-04-14 08:20发布

var array1 = ['a','b','c','d'];
var array2 = ['a','v','n','d','i','f'];

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

Just starting to learn Javascript, I can't figure out how to compare the values of array2 to those on array1 and if so replace it with the corresponded array index from array3.

To turn it like this:

array2 = ['1','v','n','4','i','f'];

But also, it has to compare the values from array1 and array2 even if the index positions are different like this:

var array1 = ['a','b','c','d'];
var array2 = ['d','v','n','a','i','f'];

Thanks for the help

7条回答
劫难
2楼-- · 2020-04-14 09:07

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

查看更多
登录 后发表回答