以相同顺序将数组元素附加到另一个数组

Appending array elements to another array in the same order

我有两个 JavaScript 阵列,一个是当前的,一个是新的。我可以将新数组中的新字符串元素附加到当前数组中,并且只能添加新元素。

例如,如果我有两个数组 currentArray = [a,d]newArray = [a,b,c,d,e],我们可以看到元素 b、c 和 e 是不同的(因此可以附加到 currentArray)。

我的 UI 允许我 select 仅追加新数组中的新元素。但目前,它仅附加到数组末尾的当前。

如果我要 select 元素 b,我希望当前数组是 currentArray = [a,b,d],而不是 currentArray= [a,d,b].

如果我select元素b,然后是c,当前数组应该是currentArray= [a,b,c,d]

如何实现这个逻辑?

你可以使用这个逻辑:

var baseArray = ["a", "b", "c", "d", "e"];

function appendEl(arr, element){

  // Parse through baseArray for every possible element.
    return baseArray.filter(function(el){
    // If element is in arr or is the element itself.
    if(arr.indexOf(el)!=-1 || el==element) return true;
    else return false;

  });

}

Fiddle