简体   繁体   中英

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"]

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]);
    }
}

This solution is easy to understand, it simply uses nested for-loops to get the desired output:

var data = [];  // This will be the new array
let test2d =    // This is your 2D array
[  
  ["foo", "bar"],
  ["baz", "biz"]
]

// Here we use nested for-loops to add the items to data[] in the desired order
for(var i = 0; i < test2d.length; i++) {
    for(var j = 0; j < test2d[0].length; j++) {
        data.push(test2d[j][i]);
    }
}

console.log(data); // Print the output :)

The data array is now equal to: [ "foo", "baz", "bar", "biz" ]

Hope this is helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM