Processing multiple nested arrays

Hello everyone,

I have an input with nested arrays with the structure as shown below:

The main array has 6 elements. Each of the main 6 elements has 251 sub-arrays. And each of the 251 sub-array has 4 elements.

I would like to transform the array in such a way that the output array has 251 elements with each element having the the individual element from the main array. For example, if we consider
Input:
[[1,2,3,4....251],[1,2,3,4....251],.........[1,2,3,4....251],[1,2,3,4....251]],

I would like to to be transformed as
output:
[[1,1,1,1...1],[2,2,2,....2].......[251,251,251,....251]

How can this be done?

Thank you for your time

Regards,

Sid

If you supply a small example of the array you wish to transform maybe someone will take a crack at it. But I doubt anyone would want to create the sample as that would be your job.

1 Like

May be this way. Can't say anything about performance

/*
msg.payload = [
    ['a','b','c','d'],
    ['aa','bb','cc','dd'],
    ['aaa','bbb','ccc','ddd'],
    ['aaaa','bbbb','cccc','dddd']
]
*/

let result = Array.from(Array(msg.payload.length), () => []);
msg.payload.forEach((arr) => {
    arr.forEach((a,i) => {
        result[i].push(a)
    })
})

msg.payload = result
return msg;

Only needs to be:

const result = []

I understood that the task is to swap rows with columns in multidimensional array. So the result has same structure with empty arrays in wrapper array prepared before iteration.
Internal arrays can of course be added at first level of iteration but is there any difference I don't know.

Edit:
Seems that I have misread the task so it is far from solution ...

This way then

let result = []
msg.payload.forEach((arr) => {
    arr.forEach((a,i) => {
        if(!result[i]){
            result.push([])
        }
        result[i].push(a)
    })
})

msg.payload = result
return msg;
1 Like

Yes.. that works.. Thank you very much :slightly_smiling_face:

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.