Home > Back-end >  Flatten List without using Flat() function in Javascript
Flatten List without using Flat() function in Javascript

Time:07-08

I am trying to flatten a given data without using flat() function. here is my implementation

function flatten(ary) {
    var ret = [];
   
    console.log(JSON.parse(ary))
    for(var i = 0; i < ary.length; i  ) {
        if(Array.isArray(ary[i])) {
            ret = ret.concat(flatten(ary[i]));
        } else {
            ret.push(ary[i]);
        }
    }
    return ret;
}

console.log(flatten(["This is a string", 1, 2, [3], [4, [5, 6]], [[7]], 8, "[10, 11]"]));

expected output ["This is a string",1,2,3,4,5,6,7,8,10,11]

it works without the string . But when I put the string inside the argument it doesnt works.I can not use flat() function that is the main problem. Thank you

CodePudding user response:

The error you see is because you are trying to interpret This is a string as JSON. What you should do, if you want to interpret JSON values, is to try-catch the JSON.parse that way the error will be silenced. Here's the modified code.

function flatten(ary) {
    var ret = [];
   

    for(var i = 0; i < ary.length; i  ) {
        let value = ary[i];
        try{
           value = JSON.parse(value);
        }catch(e){}
        if(Array.isArray(value)) {
            ret = ret.concat(flatten(value));
        } else {
            ret.push(value);
        }
    }
    return ret;
}

console.log(flatten(["This is a string", 1, 2, [3], [4, [5, 6]], [[7]], 8, "[10, 11]"]));

CodePudding user response:

You can flatten an array like this:

function flatten(a) {
    while (a.some(Array.isArray))
        a = [].concat(...a)
    return a
}

a = ["This is a string", 1, 2, [3], [4, [5, 6]], [[7]], 8, "[10, 11]"]
console.log(flatten(a));

If there are possible json strings in the array you'd like to parse, do that beforehand, for example:

function tryParse(x) {
    try {
        return JSON.parse(x)
    } catch(e) {
        return x
    }
}

a = ["This is a string", 1, 2, [3], [4, [5, 6]], [[7]], 8, "[10, 11]"]

a = a.map(tryParse)
console.log(a)

  • Related