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

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

    function replaceDuplicates(array1, array2, array3) {
    
        // array3 can't be smaller than array1!
        if (array3.length < array1.length) throw new Error('array3 < array1');
    
        // Loop through all the items in array1...
        for (var i = 0; i < array1.length; i++) {
    
            // Check if the item in array2 matches...
            if (i < array2.length && array2[i] === array1[i]) {
    
                // And if it does replace array1's item with array3's item!
                array1[i] = array3[i];
    
            }
        }
    }
    
    
    var array1 = ['a','b','c','d'];
    var array2 = ['a','v','n','d','i','f'];
    var array3 = ['1','2','3','4','5','6'];
    
    replaceDuplicates(array1, array2, array3);
    
    console.log(array1); // ['1','v','n','4','i','f']
    

提交回复
热议问题