Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 合并/展平数组(Merge/flatten an array of arrays)

I have a JavaScript array like:

(我有一个像这样的JavaScript数组:)

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

How would I go about merging the separate inner arrays into one like:

(我将如何将单独的内部数组合并为一个类似的数组:)

["$6", "$12", "$25", ...]
  ask by Andy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use concat to merge arrays:

(您可以使用concat合并数组:)

 var arrays = [ ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"] ]; var merged = [].concat.apply([], arrays); console.log(merged); 

Using the apply method of concat will just take the second parameter as an array, so the last line is identical to this:

(使用concatapply方法将仅将第二个参数作为数组,因此最后一行与此相同:)

var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);

There is also an experimental Array.prototype.flat() method (not yet part of the ECMAScript standard) which you could use to flatten the arrays, although it is only available in Node.js starting with version 11, and not at all in Edge .

(还有一个实验性的Array.prototype.flat()方法(尚不是ECMAScript标准的一部分),您可以使用它来展平数组,尽管它仅在从版本11开始的Node.js中可用,而在所有版本中均不可用。边缘 。)

 const arrays = [ ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"] ]; const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. console.log(merge3); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...