easyJS ES6+#105

Transformador (restructure object)

Prompt

Transform { nombres: ["Ana","Bob"], edades: [25,30] } into [{ id: 1, nombre: "Ana", edad: 25 }, { id: 2, nombre: "Bob", edad: 30 }]

Solution

function transform(data) {
  return data.nombres.map((nombre, i) => ({
    id: i + 1,
    nombre,
    edad: data.edades[i],
  }))
}
Mentor's take

This is a zip — combining parallel arrays into an array of records by shared index. It's the shape of half of real-world data plumbing: an API returns columnar data, the UI wants rows. The idiom is map with its second argument (the index) used to reach into the sibling array: data.edades[i]. One pass, O(n) time, O(n) space, and there's no asymptotically better option — the value of this question is idiom fluency, not complexity.

Details interviewers watch for:

  • map over an imperative loop with push — both are O(n), but map states intent ("same length out as in") and produces the new array without mutation ceremony.
  • Arrow returning an object literal needs parentheses: i => ({ ... }). Without them the braces parse as a function body and you silently return undefined for every element — a syntax trap that has burned everyone once.
  • Shorthand property nombre instead of nombre: nombre — small, but it signals ES6 fluency, which is what this category probes.

Mention the contract question out loud: what if the arrays have different lengths? Here edades[i] would be undefined; in production you'd validate or zip to the shorter length.

Red flag: forgetting the parentheses around the returned object literal, or building the result with an index-mutating for loop and result[i] = when map is the direct expression of the transformation.

Say it: "It's a zip: map over one array and index into the other — with the arrow body wrapped in parentheses so the object literal isn't parsed as a block."