Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a bidimensional array to a 1D array alternating their values

I have a bidimensional array like this:

let test2d = [
  ["foo", "bar"],
  ["baz", "biz"]
]

If I want to convert this 2D array into 1D array (not alternating their values), I can do it on two ways:

First way:

let merged = test2d.reduce( (prev, next) => prev.concat(next) )
console.log(merged) // ["foo", "bar", "baz", "biz"]

Second way:

let arr1d = [].concat.apply([], test2d)
console.log(arr1d) // ["foo", "bar", "baz", "biz"]

Question: How can I get a 1D array but with their values alternated? I mean like this:

["foo", "baz", "bar", "biz"]
like image 277
robe007 Avatar asked May 23 '18 21:05

robe007


3 Answers

You can use the zip function defined here: Javascript equivalent of Python's zip function

let zip= rows => rows[0].map((_,c)=>rows.map(row=>row[c]))

So you can call:

let arr1d = [].concat.apply([], zip(test2d))

Here's the full code:

let test2d = [ ["foo", "bar"], ["baz", "biz"] ]

let zip = rows => rows[0].map((_, c) => rows.map(row => row[c]))

let arr1d = [].concat.apply([], zip(test2d))

console.log(arr1d)
like image 120
CrociDB Avatar answered Nov 14 '22 21:11

CrociDB


You could take an array for each index and concat the arrays at the end.

var array = [["foo", "bar"], ["baz", "biz"]],
    result = [].concat(...array.reduce((r, a) => {
        a.forEach((v, i) => (r[i] = r[i] || []).push(v));
        return r;
    }, []));

console.log(result);
like image 39
Nina Scholz Avatar answered Nov 14 '22 20:11

Nina Scholz


Why not use a regular for loop? This is efficient and easiest to read.

var arr1d = [];
for (let i = 0; i < test2d[0].length; i++) {
    for (let j = 0; j < test2d.length; j++) {
        arr1d.push(test2d[j][i]);
    }
}
like image 29
patstuart Avatar answered Nov 14 '22 21:11

patstuart