Home > Software design >  Javascript how to implement n-dimensions to removeOne with non-recursive
Javascript how to implement n-dimensions to removeOne with non-recursive

Time:12-17

input

console.log(removeOne([]));
console.log(removeOne([1, 3, 1, 2, 1]));
console.log(removeOne([1, 4, [1, 5, 1, 2]]));
console.log(removeOne([1, 1, [1, 3, [1, 1, 4, 1], 2]]));

output

[]
[ 3, 2 ]
[ 4, [ 5, 2 ] ]
[ [ 3, [ 4 ], 2 ] ]


function removeOne(ary) {

let result=[];
let stateu=[];
let statej=[];
for(let i=0;i<ary.length;i  ){
    
    if(ary[i] instanceof Array){
        let tmp=[]
        let tmp1=[]
        let j=ary[i].slice();
        
        for(let u=0;u<j.length;u  ){
            
            console.log("u  " u);
            if(j[u] instanceof Array){
                stateu.push(u);
                
                statej.push(j);
                j=j[u];
                u=-1;
                
                result.push(tmp);
                tmp=[];
                
            }
            else if(j[u]!=1){
                tmp.push(j[u]);
                console.log("j   " j);
                if((u 1)==j.length){
                    
                    result.push(tmp);
                    
                }
                
            }
            else if((u 1)==j.length){
                
                j=statej.pop();
                u=stateu.pop();
                console.log("j[u]    " j);
                
            }
        }
        
    }
    else if(ary[i]!=1)
        result.push(ary[i]);
}

return result;

}

1.It takes me a lot of day to think, I have implemented it by using recursive. But how to fullfill it by just using the loop?

2.It has to be implemented by JavaScript.

//update over here.

3.I have implemented the elementary prototype of the non-recursive result.

4.stateu and statej are two liked-stack just use push and pop to store the previous u and j as ary[0,1,.....n] belongs to Array.

5.I set u=-1 because the next round u will plus 1. Then go down to new nested-array.

6.j=ary[i] that can be processed the specific array and does for-loop.

7.Can somebody adjust my code to reach the right Answer?

CodePudding user response:

Kind of "hacking" way.

Of couse there is recursion under the hood of stringify and parse.

const removeOne = (coll) => JSON.parse(
  JSON.stringify(coll)
  .replaceAll('1,', '')
  .replaceAll(',1', '')
);

console.dir(removeOne([1, 1, [1, 3, [1, 1, 4, 1], 2]]), {depth: null});
//[ [ 3, [ 4 ], 2 ] ]

  • Related