Skip to content
Fix Code Error

Merge/flatten an array of arrays

March 13, 2021 by Code Error
Posted By: Anonymous

I have a JavaScript array like:

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

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

["$6", "$12", "$25", ...]

Solution

You can use concat to merge arrays:

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:

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

There is also the Array.prototype.flat() method (introduced in ES2019) 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 Internet Explorer.

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);
    
Answered By: Anonymous

Related Articles

  • Pandas Merging 101
  • Setting up and using Meld as your git difftool and mergetool
  • How to "properly" create a custom object in JavaScript?
  • How does JavaScript .prototype work?
  • How do I keep only the first map and when the game…
  • What is the 'new' keyword in JavaScript?
  • For-each over an array in JavaScript
  • Git merge with force overwrite
  • Why does git perform fast-forward merges by default?
  • Fastest way to flatten / un-flatten nested JSON objects
  • What does this symbol mean in JavaScript?
  • Vuetify grid system row management
  • Polymer: Vers simple data binding doesn't work in…
  • How do I include certain conditions in SQL Count
  • Is the book's answer-sheet wrong about this "flatten…
  • Coffeescript class extend more bloat than Backbone extend
  • How do I merge two dictionaries in a single…
  • When would you use the different git merge strategies?
  • Git workflow and rebase vs merge questions
  • Smart way to truncate long strings
  • Git Cherry-pick vs Merge Workflow
  • SQLGrammarException:error executing work ORA-01722:…
  • TypeScript metadata reflection references other…
  • How to get the correct wights?
  • Ember build failing
  • How to find out what is referencing a detached DOM…
  • Chrome / Safari not filling 100% height of flex parent
  • INNER JOIN vs LEFT JOIN performance in SQL Server
  • POI Word Unable to merge newly created cell vertically
  • How do I turn a nested dict of lists (with dicts)…
  • Recalculate merge conflicts (ie. how to generate…
  • How to add multiple classes to an element based on…
  • Class vs. static method in JavaScript
  • Cannot write if or select above begin on a procedure
  • JavaScript OOP in NodeJS: how?
  • How does the "this" keyword work?
  • Conditional rendering based on checkbox input in Vue.js
  • Backbone Collection.fetch gives me Uncaught…
  • Union of multiple Database queries with same parameters
  • How do JavaScript closures work?
  • explain backbone object and class creation pattern
  • What are the undocumented features and limitations…
  • can I run multiple DataFrames and apply a function…
  • VueJS components ref is undefined at all stages
  • In plain English, what does "git reset" do?
  • Python: pandas merge multiple dataframes
  • How do I 'overwrite', rather than 'merge', a branch…
  • Add a popup modal to vuetify vue.js
  • Practical uses of git reset --soft?
  • What is your most productive shortcut with Vim?
  • I want to solve the javascript OOP problems, but my…
  • How do I create a custom Error in JavaScript?
  • How to recover stashed uncommitted changes
  • Python Inserting headers for CSV file when…
  • Merge two dataframes by index
  • How can I access and process nested objects, arrays or JSON?
  • What is the scope of variables in JavaScript?
  • Got ValueError: Attempt to convert a value (None)…
  • Active tab issue on page load HTML
  • (SETF L (FLATTEN L)) should be a lambda expression error
  • How to get rid of SourceMapConcat build error in emberjs?
  • Get the name of an object's type
  • Snowflake - Lateral Flatten creating duplicate rows
  • How to bind repeating nested templates to complex models
  • Flatten an irregular list of lists
  • Logging best practices
  • Vuetify grid layout - How to fill height of element in grid
  • Merge, update, and pull Git branches without using checkouts
  • Avoid multiple copy of data when composing objects…
  • How to create the branch from specific commit in…
  • Property or method "key" is not defined on the…
  • Merge Sort in C using Recursion
  • Git pull a certain branch from GitHub
  • Merge development branch with master
  • From ND to 1D arrays
  • Programmatically generate url from path and params
  • Aborting a stash pop in Git
  • Create IGrouping within IGrouping
  • How do I correctly clone a JavaScript object?
  • How to prevent scrolling the whole page?
  • how does git know there is a conflict
  • What's the best way to get the last element of an…
  • Best way to bind textfield to a model in ember
  • How to Watch Object Property within a Vue Plugin
  • When should I use cross apply over inner join?
  • How to compare arrays in JavaScript?
  • Python Converting JsonL to CSV File Permission Error 13
  • C++ Switch statement to assign struct values
  • How to merge two arrays in JavaScript and de-duplicate items
  • OpenCL - Approximation of Pi via Monte Carlo…
  • What exactly does the "u" do? "git push -u origin…
  • Determine if string is in list in JavaScript
  • jQuery Mobile: document ready vs. page events
  • What are the nuances of scope prototypal /…
  • How to UPSERT (MERGE, INSERT ... ON DUPLICATE…
  • Replace transparency in PNG images with white background
  • Finding what branch a Git commit came from
  • Why does git say "Pull is not possible because you…
  • How to make a floated div 100% height of its parent?
  • How to add space between cards in same row in vuetify

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to initialize an array’s length in JavaScript?

Next Post:

Is there a tag to turn off caching in all browsers?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error