合并数组仅添加新元素

时间:2018-08-05 15:24:55

标签: javascript arrays

嘿,我正在为一件非常简单的事情而烦恼。我有几个数组

//input

var array1 = ["white", "white", "yellow"];
var array2 = ["white", "white", "yellow", "red"];
var array3 = ["white", "white", "yellow", "orange"];

//desired output

var result = ["white", "white", "yellow", "red", "orange"];

这应该是一个简单的问题,但是我只是无法解决这个问题。我尝试使用第一个数组的快照,然后查看快照数组中是否已存在该颜色,然后将其从快照中删除,再将其放入另一个快照中,等等。。。甚至无法使它正常工作,因为我从快照中删除了所有“白色”颜色,而不仅仅是出现错误的一种或其他情况。

有人可以给我第二个角度吗,因为我在墙上的atm上奔跑

我最后一次要求提供代码的尝试

    let attacks = entry.attacks;
    if(attacks !== undefined){
        let lastSnapshot = [];

        attacks.forEach(attack => {
            if(lastSnapshot.length === 0){
                attack.forEach(attackColor => {
                    lastSnapshot.push(attackColor)
                })                        
            }else{
                let newSnapshot = [];
                attack.forEach(attackColor => {
                    var start_index = lastSnapshot.findIndex(attackColor)
                    if(start_index !== -1){
                        var number_of_elements_to_remove = 1;
                        lastSnapshot.splice(start_index, number_of_elements_to_remove);                                
                    }

                    newSnapshot.push(attackColor)
                })
                lastSnapshot = newSnapshot;                              
            }
        })
    }

2 个答案:

答案 0 :(得分:4)

您可以将reduce用于数组,并将forEach用于数组的单个项目,以将项目添加到r

然后,使用哈希表存储访问的项目及其临时结果数组r的最后一个索引。如果未找到任何项目,则推送实际值。

var array1 = ["white", "white", "yellow"],
    array2 = ["white", "white", "yellow", "red"],
    array3 = ["white", "white", "yellow", "orange"],
    result = [array1, array2, array3].reduce((r, a) => {
        var indices = Object.create(null);
        a.forEach(b => {
            var p = r.indexOf(b, indices[b] || 0);
            indices[b] = p === -1 ? r.push(b) : p + 1;
        });
        return r;
    });
    
console.log(result);

答案 1 :(得分:1)

您也可以使用SetSpreadforEach尝试这种方式。

var array1 = ["white", "white", "yellow"];
var array2 = ["white", "white", "yellow", "red"];
var array3 = ["white", "white", "yellow", "orange"];
var merged = Array.from(new Set(array2.concat(array3)));
var desired = [...array1];
merged.forEach(function(element, index) {
  if (array1.indexOf(element) == -1) {
    desired.push(element);
  }
})
console.log(desired)

传播语法: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

设置: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

forEach: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach