0

I have an array like below

var arr = [["a", "b"],[1],[5,6]];

I would like to convert it to plain JSON like below

arr = [
     ["a","a","b","b"]
     [1,1,1,1]
     [5,6,5,6]
]

The logic is

Under each item of first array element all the elements are sub elements, under next each array items of [1], [5,6] are sub elements

a->1->[5,6]
b->1->[5,6]

if var arr = [["a", "b"],[1,2],[5,6]]; then

a->[1]->[5,6]
a->[2]->[5,6]

like the same with element b also. I am struck, as I don't know how to proceed

1
  • if it should be like a->1->[5,6], b->1->[5,6]then your final array will be [[5,6],[5,6]] since [a,b] = [[1],[1]] = [[5,6],[5,6]] Commented Aug 21, 2013 at 7:26

1 Answer 1

1

Like this?:

var arr = [["a", "b"],[1],[5,6]];

var convert2PlainArray = function(array){
    var totalLength = 1,
        plainArray = [];
    for(var i=0;i<array.length; i++){
        totalLength*=array[i].length;
    }
    for(var i=0;i<array.length; i++){
        var currentElementLength = totalLength/array[i].length,
            tempArray = [];
        for(var e=0;e<array[i].length; e++){
            for(var l=0;l<currentElementLength; l++)tempArray.push(array[i][e]);
        }
        plainArray.push(tempArray);
    }
    return plainArray;
}

alert(JSON.stringify(convert2PlainArray(arr)));

Test it on fiddle: http://jsfiddle.net/GMJzW/

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the response, but in the response last array item should be [5,6,5,6] instead of [5,5,6,6]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.