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"]
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)
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);
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With