最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert a bidimensional array to a 1D array alternating their values - Stack Overflow

programmeradmin1浏览0评论

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

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"]
Share Improve this question asked May 23, 2018 at 21:24 robe007robe007 3,9674 gold badges38 silver badges61 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

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!

发布评论

评论列表(0)

  1. 暂无评论