How to Flatten Nested Array in JavaScript

How to flatten nested array in javascript?

This is an alternative to recursion (see jsfiddle here) and should accept any level of depth which avoids stack overflow.

var array = [[0, 1], [2, 3], [4, 5, [6, 7, [8, [9, 10]]]]];console.log(flatten(array), array); // does not mutate arrayconsole.log(flatten(array, true), array); // array is now empty
// This is done in a linear time O(n) without recursion// memory complexity is O(1) or O(n) if mutable param is set to falsefunction flatten(array, mutable) { var toString = Object.prototype.toString; var arrayTypeStr = '[object Array]'; var result = []; var nodes = (mutable && array) || array.slice(); var node;
if (!array.length) { return result; }
node = nodes.pop(); do { if (toString.call(node) === arrayTypeStr) { nodes.push.apply(nodes, node); } else { result.push(node); } } while (nodes.length && (node = nodes.pop()) !== undefined);
result.reverse(); // we reverse result to restore the original order return result;}

How to flatten the nested array of of objects and duplicate the parent

You can use Array.flatMap() to iterate the objects, and then iterate the attributes with Array.map(), and combine with the rest of the object. The Array.flatMap() would also flatten the array of arrays to a single array.

const fn = arr => arr.flatMap(({ attributes, ...rest }) => 
attributes.map(o => ({
...rest,
...o
}))
)

const products = [{"productId":"1","attributes":[{"variant":"red","price":"134.00"}]},{"productId":"2","attributes":[{"variant":"green","value":"3400.00"},{"variant":"pink","price":"342.00"}]}]

const result = fn(products)

console.log(result)

Merge/flatten an array of arrays



ES2019

ES2019 introduced the Array.prototype.flat() method which you could use to flatten the arrays. It is compatible with most environments, 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);

Flatten nested array key value pairs without specifying each key in Javascript

You can use Object.entries to get all the key value pairs and work with that.

let arr=[{force_x:[1,2,3],force_y:[.3,.4,.5]},{force_x:[4,5,6],force_y:[0,0,0]},{motion_x:[.7,.7,.7]}];
let res = arr.flatMap(x => {
const entries = Object.entries(x);
return entries[0][1].map((_, i) => Object.fromEntries(
entries.map(([k, v]) => [k, v[i]])));
});
console.log(res);

dynamically flatten nested array of objects javascript

You can use recursion to flatten the objects into a single level object and pass that function to map to get an array of flattened object

const data = [{    parKeyA: "parValA",    parKeyA1: {      chiKeyA1: "chiValA1",      chiKeyA2: "chiValA2"    },    parKeyA2: {      chiKeyA3: "chiValA3"    }  },  {    parKeyB: "parValB",    parKeyB1: {      chiKeyB1: "chiValB1",      chiKeyB2: {}    }  }]

let flatten = (obj, final = {}) => { for (let key in obj) { if (typeof obj[key] === 'object' && obj[key] != null) { flatten(obj[key], final) } else { final[key] = obj[key] } } return final}
console.log(data.map((v) => flatten(v)))

JS how to flatten a nested array

You need to return the reduced array by taking the handed over array arrayOfArrays.

function flattenArray(arrayOfArrays) {  
return arrayOfArrays.reduce(function(a, b) {
return a.concat(b);
}, []);
}

For multiple nested arrays, you need to check for array and use a recursion of the function.

function deepFlattenArray(arrayOfArrays) {    return arrayOfArrays.reduce(function(a, b) {        return a.concat(Array.isArray(b) ? deepFlattenArray(b) : b);    }, []);}
function flattenArray(arrayOfArrays) { return arrayOfArrays.reduce(function(a, b) { return a.concat(b); }, []);}
console.log(deepFlattenArray([[[1, 2], [3, [4, 5], 6], 7], 8]));console.log(flattenArray([[[1, 2], [3, [4, 5], 6], 7], 8]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Convert nested array of objects to a flat structure using recursion : Javascript

You can do it recursevly with passing the array reference by every recurse

const arr1 = [
{
name: "parent",
children: [
{
name: "child1",
children: [
{
name: "granchild1",
children: [],
class: "level-2 leaf",
config: {
name: "granchild1",
value1: false,
value2: false
}
}
],
class: "level-1 leaf",
config: {
name: "child1",
value1: false,
value2: false
}
},
{
name: "child2",
children: [],
class: "level-1 leaf",
config: {
name: "child2",
value1: false,
value2: false
}
}
],
class: "level-0 group",
config: {
name: "parent",
value1: false,
value2: false
}
}
];

let collect = (arr, result = []) => {

arr.forEach(prop => {
result.push({...prop.config})
collect(prop.children, result)
})
return result
}

let result = collect(arr1)

console.log(result)


Related Topics



Leave a reply



Submit