← Back Home

Flatten Arrays in Javascript

  1. javascript
  2. flatten array
  3. nodejs

Yesterday, I encountered Array.prototype.flat for the first time. I didn’t know it existed😱😱😱!! Very cool function…

Its job is to flatten nested arrays into a single array.

var a = [[1, 2], [[3, 4], [5, 6]], 7, 8];
var b = a.flat()
//[1, 2, 3, 4, 5, 6, 7, 8]

It can also flatten upto a given level.

var a = [[1, 2], [[3, 4], [5, 6]], 7, 8];
var b = a.flat(1)
//[1, 2, [3, 4], [5, 6], 7, 8]

This was extremely useful when I was trying to flatten an array for the ElasticSearch Bulk API. I had a list of objects that looked like this:

var bulkOps = [
        [{ "delete" : { "_index" : "test", "_id" : "2" } }],
        [{ "create" : { "_index" : "test", "_id" : "3" } }, { "field1" : "value3" }],
        [{ "update" : {"_id" : "1", "_index" : "test"} }, { "doc" : {"field2" : "value2"} }]
    ];

bulkOps.flat(1) was all I needed to transform it into the shape that the Bulk API needed.

Note that in this case bulkOps.flat() would have issues flattening the inner objects since bulkOps is not a nested list all the way down.