【问题标题】:iterate two recursive arrays [array item contains another array] simulataniously in javascript在javascript中同时迭代两个递归数组[数组项包含另一个数组]
【发布时间】:2019-07-15 08:38:44
【问题描述】:

我有两个对象数组,它可能包含另一个对象数组,我如何迭代两个数组并相互比较???

interface items {
name:string;
subItems:items[];
value:string;
}

Array A=['parent1',['child1',['child2',['child3',[],'value3'],'value2'],'value1']];

Array B=['parent1',['child1',[null,['child3',[],'value3'],'value2'],'value1']];

预期结果:

Array B=['parent1',['child1',['child2',['child3',[],'value3'],'value2'],'value1']];

这两个数组之间的区别是数组 B child2 名称为空,所以我想与两个数组进行比较,如果名称为空,则从第一个数组中复制名称..

我们如何同时迭代两个可能包含子数组的数组。

注意:有时我的数组包含 N NUMBER OF CHILDREN'S,

我认为我们可以使用递归函数,但我们如何迭代数组的级别?

我尝试了多个 for 和 forEach 循环,但对我不起作用

【问题讨论】:

    标签: javascript arrays typescript loops recursion


    【解决方案1】:

    您可以将两个数组放入一个迭代元素并查找数组的函数中,然后再次调用此函数或检查值,如果不同,则更新数组。

    function compareAndUpdate(a, b) {
        a.forEach((v, i) => {
            if (Array.isArray(v)) return compareAndUpdate(v, b[i]);
            if (b[i] !== v) b[i] = v;
        });
    }
    
    var a = ['parent1', ['child1', ['child2', ['child3', [], 'value3'], 'value2'], 'value1']],
        b = ['parent1', ['child1', [null, ['child3', [], 'value3'], 'value2'], 'value1']];
    
    compareAndUpdate(a, b);
    
    console.log(b);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 非常感谢你的想法,我按照我的代码做了一些它的工作就像魅力
    【解决方案2】:

    这是 Javascript 解决方案。这可能会有所帮助:

        function recursion(arr1,arr2){
    
           for(let index = 0; (arr1.length>index && arr2.length>index);index++){
                if(Array.isArray(arr1[index]) && Array.isArray(arr2[index])){
                    recursion(arr1[index],arr2[index]);
                }else if(arr1[index] !== arr2[index]){
                    arr1[index] = arr2[index];
                }
           }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 2013-05-06
      • 2011-02-17
      • 2021-08-07
      • 1970-01-01
      • 2016-05-16
      • 2021-04-11
      相关资源
      最近更新 更多