javascript group array by field “Variable” - const dat = [ { “Variable”: “Trimmed Can…
- User
javascript group array by field “Variable” - const dat = [ { “Variable”: “Trimmed Can Height”, “Value”: “1” }, { “Variable”: “Trimmed Can Height”, “Value”: “165” }, { “Variable”: “Wtf”, “Value”: “10” }, { “Variable”: “zxc”, “Value”: “10” }, { “Variable”: “zxc”, “Value”: “10” }, { “Variable”: “zxc”, “Value”: “10” } ]
- Assistant
To group the array
datby the field "Variable", you can use the following JavaScript code:const groupedDat = dat.reduce((acc, obj) => { const key = obj["Variable"]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); console.log(groupedDat);This code uses the
reducemethod to iterate over thedatarray and group the objects by the "Variable" field. The resultinggroupedDatobject will have keys that correspond to the unique values of the "Variable" field, and each key will contain an array of objects that have that specific "Variable" value.When you run this code, you will see the grouped data displayed in the console with the objects grouped by the "Variable" field.