比较 3 个数组以生成一个新字符串

Compare 3 arrays to make a new string

我有 3 个数组

array1 = [a,b,c,d,e,f]
array2 = [a,b,d,f]
array3 = [g,h]

我如何找出 array2 中的哪些地方与 array1 不匹配,然后从 array3 中插入​​一个元素?

所以输出看起来像

array4 = [a,b,g,d,h,f]


var EnglishArray = [<p>,This is a longer description. This will describe the item in greater detail.,</p>,<span please no translated Large donkey>,cat,</span>,<div>,test,<large>,<idk>,&bull;,Hello worlds,<end?>]
var HTMLTags = [<p>,</p>,<span please no translated Large donkey>,</span>,<div>,<large>,<idk>,&bull;,<end?>]
var translations = [Esta es una descripción más larga. Esto describe el tema con mayor detalle.,gato,prueba,Hola mundos]

function newString(EnglishArray, HTMLTags, translations){
  var array4 = EnglishArray;
  var j = 0;
  for (var i = 0; i < EnglishArray.length; i++) {
    if(HTMLTags[i] != EnglishArray[i]){
      array4.splice(i, 1, translations[j]);
      j++;
      i++;
    }
  }
  newString = array4.join('');
  return newString;
}

它给我的输出是

<p>Esta es una descripción más larga. Esto describe el tema con mayor detalle.</p>gatocatprueba<div>Hola mundos<large>&bull;<end?>

而不是

<p>Esta es una descripción más larga. Esto describe el tema con mayor detalle.</p><span please no translated Large donkey>gato</span><div>prueba<large><idk>&bull;Hola mundos<end?>

当我在小得多的规模上尝试这个时,它工作正常。但是好像标签越多,翻译出来的错误就越多。在它变得太长之后,它将开始用英语重复最后几个单词。

这应该可行,但它会在此过程中破坏 array2 和 array3,因此您可能需要制作一个副本(array2.slice() 创建副本,简单赋值不会)。

const array1 = ['a','b','c','d','e','f']
const array2 = ['a','b','d','f']
const array3 = ['g','h']
console.log(array1.map(x => array2[0] === x ? array2.shift() : array3.shift()))

您可以检查该值是否包含 array2,如果不包含 array3.

的元素

var array1 = ['a', 'b', 'c', 'd', 'e', 'f'],
    array2 = ['a', 'b', 'd', 'f'],
    array3 = ['g', 'h'],
    result = array1.map(v => array2.includes(v) ? v : array3.shift());
    
console.log(result);

没有 mapincludes

var array1 = ['a', 'b', 'c', 'd', 'e', 'f'],
    array2 = ['a', 'b', 'd', 'f'],
    array3 = ['g', 'h'],
    result = [],
    i,
    l = array1.length;

for (i = 0; i < l; i++) {
    result.push(array2.indexOf(array1[i]) === -1 ? array3.shift() : array1[i]);
}

console.log(result);

其他解决方案,对人们来说更具可读性。

array1 = ["a","b","c","d","e","f"]
array2 = ["a","b","d","f"]
array3 = ["g","h"]

j=0;

for (i=0 ; i < array1.length ;i++){
    if (array2[i]!==array1[i])
        {
        array2.splice(i,0, array3[j]);
        j++;
        }
}

console.log(array2);`
    var array1 = ['a','b','c','d','e','f']
    var array2 = ['a','b','d','f']
    var array3 = ['g','h']
    var array4 = array1.concat(array2,array3); 
    var set = new Set(array4);
    array4 = Array.from(set);