Compare Two Arrays And Replace Duplicates With Values From A Third Array
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 compa
Solution 1:
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);
Solution 2:
You can use map()
on array2 and see if current element is same as element in array1 with same index if it is return element from array3 with index of i
else return current element or e
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.map(function(e, i) {
return e == array1[i] ? array3[i] : e;
})
console.log(result)
Solution 3:
Use Array#map
array2.map((v, i) => v === array1[i] ? array3[i] : v);
Solution 4:
there are many forms, this is a basic form:
var array1 = ['a','b','c','d'];
var array2 = ['a','v','n','d','i','f'];
var array3 = ['1','2','3','4','5','6'];
var result = [];//define array of resultfor(var i=0;i<array2.length;i++){//Iterate the array2if(array2[i] == array1[i])//Compare if array1 in index 'i' with array2 in index 'i'
result[i] = array3[i];//if true put in result in index 'i' from array3else
result[i] = array2[i];//else put in result in index 'i' from array2
}
console.log(result);//show in console the result
Solution 5:
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];
}
})(newSet(array1)));
console.log(array2);
Post a Comment for "Compare Two Arrays And Replace Duplicates With Values From A Third Array"