合并数组仅添加新元素

肯尼

嘿,我为应该很简单的事情而烦恼。我有几个数组

//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"];

这应该是一个简单的问题,但我只是无法解决这个问题。我尝试使用第一个数组的快照,然后查看快照数组中是否已存在该颜色,将其从快照中删除,将其放置在另一个快照中,等等。。。由于我要删除快照中的所有“白色”颜色,而不仅仅是出现错误的一种或多种其他东西,因此甚至无法使用。

有人可以给我第二个角度吗,因为我在墙上的自动柜员机上奔跑

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

    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;                              
            }
        })
    }
妮娜·斯科茨(Nina Scholz)

您可以使用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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章