← Daily Logs
GreatFrontEnd

Implement fromPairs

EasyJul 2, 2026lodasharraysobjects

Lodash's `_.fromPairs` — the inverse of `Object.entries`. Given a list of `[key, value]` tuples, build the object they describe. It's a one-pass reduction with no edge cases worth naming: destructure each pair, assign, move on.

The problem

Write `fromPairs(pairs)` that takes an array of two-element `[key, value]` arrays and returns the object composed from them: `fromPairs([['a', 1], ['b', 2], ['c', 3]])` → `{ a: 1, b: 2, c: 3 }`.

There's no real trap here — it's the mirror image of `Object.entries`, which most engineers already reach for in the other direction. The only thing to get right is handling a duplicate key correctly: later pairs should win, the same way object literals and `Object.assign` resolve repeated keys.

The approach

Start with an empty object and walk the array once. For each pair, destructure it into `[key, val]` and assign `obj[key] = val`. Plain assignment naturally gives 'last pair wins' for duplicate keys, matching how object literals behave.

No accumulator library or `reduce` is needed — a `for...of` loop mutating a single object is the clearest version and runs in one linear pass over the input.

The solution

js
/**
 * Creates an object from an array of key-value pairs.
 *
 * @param {Array} pairs - An array of key-value pairs.
 * @returns {Object} - The object composed from the key-value pairs.
 */
export default function fromPairs(pairs) {
  const obj = {};
  for (let pair of pairs) {
    const [key, val] = pair;
    obj[key] = val;
  }
  return obj;
}

Time O(n)Space O(n)

All entries