javascript flatten array of object code example

Example 1: javascript array flatten

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

Example 2: flatten array object javascript

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))

//replace data with your array