flat to flatten the arrays.
Create object maps to group by group and age.
Extract individual objects per key in object map, and unwrap ages objects to arrays.
ages are numbers, and ES2015 sorts integer indexes, so the order is already sorted by age.
Note: your JavaScript data object is invalid JavaScript due to use of non-standard single quote. And there are unclosed brackets in your data. Parsed as string sanitized to JSON.
res =
Object.entries(
array.flat().reduce((res,x)=>{
const {age, group} = x
res[group] = res[group] || {}
res[group][age] = res[group][age] || []
res[group][age].push(x)
return res
},{})
).map(([k,v])=>({[k]: Object.values(v)}))
console.log(res)
<script>
array =
JSON.parse(`[
[{name:’a’,age:’4’,group:’15’},{name:’b’,age:’4’,group:’15’},
{name:’c’,age:’4’,group:’15’}],
[{name:’aa’,age:’6’,group:’12’},{name:’bb’,age:’6’,group:’12’}],
[{name:’d’,age:’5’,group:’15’},{name:’e’,age:’5’,group:’15’},
{name:’f’,age:’5’,group:’15’}],
[{name:’dd’,age:’7’,group:’12’},
{name:’ee’,age:’7’,group:’12’},{name:’ff’,age:’7’,group:’12’}]
]`.replace(/’/g,'"').replace(/(name|age|group)/g,'"$1"'))
</script>
2
solved Group array of objects in array of arrays -JS [closed]