比较两个Arrays并将Duplicates替换为第三个数组中的值
问题描述:
var array1 = ['a','b','c','d'];
var array2 = ['a','v','n','d','i','f'];
var array3 = ['1','2','3','4','5','6'];
刚开始学习Javascript,我无法弄清楚如何比较 array2 到 array1
上的那些,如果是这样的话,用 array3 $ c中的相应数组索引替换它$ c>。
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
.
如下所示:
array2 = ['1','v','n','4','i','f'];
但是,即使索引位置不同,它也必须比较array1和array2的值这个:
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'];
感谢您的帮助
答
您可以使用哈希表并检查。如果字符串未包含在哈希表中,则为该元素设置替换值。
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, 设置
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);