JavaScript flattening an array of arrays of objects

Asked
Active3 hr before
Viewed126 times

9 Answers

arraysobjectsjavascriptarray
90%

flattened will be your expected array.,If you only need simple flatten, this may works:,Recursively flatten an array:,A recursive solution for deep (nested) flattening:

You can use Array.concat like bellow:-

var arr = [
   ['object1', 'object2'],
   ['object1'],
   ['object1', 'object2', 'object3']
];
var flattened = [].concat.apply([], arr);

ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists:

[
   ['object1'],
   ['object2']
].flat() // ['object1', 'object2']
load more v
88%

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. ,A new array with the sub-array elements concatenated into it., The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ,The flat method removes empty slots in arrays:

flat()
flat(depth)
load more v
72%

Infinitely Nested Arrays,It was always complicated to flatten an array in #JavaScript. Not anymore! ES2019 introduced a new method that flattens arrays. And there's a "depth" parameter, so you can pass in ANY levels of nesting. AMAZING 🤩,Stack Overflow: Merge/flatten an array of arrays ,Flatten array of arrays with JavaScript

const nested = [
   ['📦', '📦'],
   ['📦']
];

const flattened = nested.flat();

console.log(flattened);
// ['📦', '📦', '📦']
load more v
65%

I thought this would be a pretty simple problem to solve, but I’m running in to some trouble flattening out an array of nested arrays and objects. I basically just want to flatten it out to one single array of values.,You can also use Array.prorotype.concat + apply to flatten multiple objects in an array.,Basically, I want to check if any of the array properties are empty (so that includes everything in the objects and arrays that are nested). Perhaps there could be an easier way to go about this? My thought was to map over all the items and check for ‘’. But first I need to flatten the Array!,Here’s what I did to get all the values from the array:

var flattenArray = function(data) {
   return data.reduce(function iter(r, a) {
      if (a === null) {
         return r;
      }
      if (Array.isArray(a)) {
         return a.reduce(iter, r);
      }
      if (typeof a === 'object') {
         return Object.keys(a).map(k => a[k]).reduce(iter, r);
      }
      return r.concat(a);
   }, []);
}
console.log(flattenArray(data))
75%

Say you have an array of arrays full of objects you want to flatten into one array:, Flattening array of arrays ,For flattening arrays of arrays only one level deep!, Functional programming Flattening array of arrays

Say you have an array of arrays full of objects you want to flatten into one array:

const nestedArrays: Person[][] = [
   [{
         firstName: "Andrew",
         lastName: "Smith"
      },
      {
         firstName: "Derek",
         lastName: "Maloney"
      },
   ],
   [{
      firstName: "Chris",
      lastName: "Cawlins"
   }, ],
   [{
      firstName: "Susan",
      lastName: "Sarandon"
   }, ]
]
load more v
40%

The flatMap() method applies the given callback function to each element of the existing array and returns a new array after flattening the result by one level. It is similar to calling map() and flat() methods consecutively.,The forEach() method calls a function once for each element in an array, in order. It performs a specified task on each array element. One thing to keep in mind is that, for array elements that are empty, forEach() method skips them and moves on to the next not empty element,The findIndex() method returns the index of the first element in array that satisfies the given testing function. If no element of the array satisfies the testing condition, it returns -1.,Different methods to flatten an array


let arr = [
   [1, 2],
   [3, 4],
   [5, 6][7, 8, 9],
   [10, 11, 12, 13, 14, 15]
];
load more v
22%

// flat(depth), 
// depth is optional: how deep a nested array structure 
//		should be flattened.
//		default value of depth is 1 

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
load more v
60%

Convert an array of objects into plain object in JavaScript,What is the simplest solution to flat a JavaScript array of objects into an object?,Splitting an object into an array of objects in JavaScript,Convert object to array of objects in JavaScript

Example

//code to flatten array of objects into an object
//example array of objects
const notes = [{
   title: 'Hello world',
   id: 1
}, {
   title: 'Grab a coffee',
   id: 2
}, {
   title: 'Start coding',
   id: 3
}, {
   title: 'Have lunch',
   id: 4
}, {
   title: 'Have dinner',
   id: 5
}, {
   title: 'Go to bed',
   id: 6
}, ];
const returnFlattenObject = (arr) => {
   const flatObject = {};
   for (let i = 0; i < arr.length; i++) {
      for (const property in arr[i]) {
         flatObject[`${property}_${i}`] = arr[i][property];
      }
   };
   return flatObject;
}
console.log(returnFlattenObject(notes));
load more v
48%

ES2019 introduced the Array.prototype.flat() method that creates a new array with all the elements of the subarrays concatenated to it recursively up to a specified depth.,When you don’t know the depth level, you can pass the Infinity into the flat() method to recursively concatenate all elements of the sub-arrays into the new array:,Note that the flat() method creates a new array and doesn’t change the original array:,Use the Array.prototype.flat() method to flat an array with the nested arrays.

The following shows the syntax of the flat() method:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
let newArray = arrayObject.flat([depth]) Code language: JavaScript(javascript)
load more v

Other "arrays-objects" queries related to "JavaScript flattening an array of arrays of objects"