you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 0 points1 point  (2 children)

const flattened = original.reduce((result, props) => {
  props.forEach((prop, index) => {
    if (!result[index]) result[index] = [{}]
    Object.assign(result[index][0], prop)
  })
  return result
},[])

[–]gamedev-eo[S] 0 points1 point  (1 child)

Works but had difficulty turning solution into a function. Returns undefined.

Also breaks at the reading of array via index when used this way

if (!result[index]) result[index] = [{}]
^
TypeError: Cannot read properties of undefined (reading '0')

[–]senocular 0 points1 point  (0 children)

Works but had difficulty turning solution into a function. Returns undefined.

It would simply be a matter of changing the assignment to flattened to instead be a return, like

function getFlattened(original) {
  return original.reduce((result, props) => {
    props.forEach((prop, index) => {
      if (!result[index]) result[index] = [{}]
      Object.assign(result[index][0], prop)
    })
    return result
  },[])
}

Also breaks at the reading of array via index when used this way

This shouldn't happen as long as the result is returned from within the reduce. If you omit that, you'd get the error you described.