Exercise 20: Create Object from Array of Pairs

Problem Statement

Function `fromPairs(pairs)` banao jo array of [key, value] pairs se object create kare. Example: fromPairs([["a", 1], ["b", 2]]) => {a: 1, b: 2}

Sample Output:

fromPairs([["a", 1], ["b", 2]]) => {a: 1, b: 2}
fromPairs([["x", "hello"]]) => {x: "hello"}

Solution

const fromPairs = (pairs) => {
  return pairs.reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc;
  }, {});
};

Explanation

Overall Goal:

  • Array of pairs se object create karna.

Real world:

  • Data transformation: pairs to object.
  • Array processing: pair conversion.