AniUI Academy

Build an object from keys and values

easyArrays & Objects+150 XPPractice

Parsing a CSV gives you one array of column names and one array of cell values per row. Pairing them up by position is what turns two arrays into a usable record.

Implement zipObject(keys, values). Pair keys[i] with values[i] and return a plain object. Extra values beyond the end of keys are ignored. A key with no matching value — that is, an index at or past the end of values — is skipped entirely and must not appear in the result. If the same key appears twice in keys, the later value wins. Keys become object properties, so they are coerced to strings. Two empty arrays return an empty object.

Arguments

keysArray<string>
Property names, in the order they should appear in the result.
valuesArray
Values paired with keys by position.

Returns

Object — A plain object mapping each key to its paired value. Keys without a matching value are omitted.

Examples

zipObject(["name", "role"], ["Ada", "engineer"]);
// { name: "Ada", role: "engineer" }
zipObject(["a"], [1, 2, 3]);        // { a: 1 } — extras ignored
zipObject(["a", "b", "c"], [1]);    // { a: 1 } — b and c have no value
zipObject(["a", "a"], [1, 2]);      // { a: 2 } — the later value wins

What it has to do

  • Pair keys and values by index.
  • Ignore values beyond the end of the keys array.
  • Skip keys that have no matching value, rather than storing undefined.
  • Let the later value win when a key repeats.
  • Return {} when both inputs are empty.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.