[Easy] fromPairs
March 4, 2024
Question Prompt
Implement a function named fromPairs
that takes a single argument, pairs
, which is an array of two-element sub-arrays. Each sub-array represents a key-value pair, where the first element is the key (string or symbol) and the second element is the value (any valid JavaScript data type). Your function should return a new object where each key-value pair from the pairs
array is added as a property-value pair to the object.
const pairs = [
["explain", "this"],
["help", "you"],
["keep", "growing"],
];
fromPairs(pairs);
// => { explain: 'this', help: 'you', keep: 'growing' }
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
we can begin by creating an empty object result
to store the final key-value pairs. This object will serve as the foundation for our transformed data.
Then, we can use for...of
loop, to efficiently iterate through each element in the pairs
array. And use destructuring assignment ([key, value]
) to elegantly extract the key and value from each sub-array within the loop.
And through result[key] = value
, we dynamically create a new property in the result
object with the extracted key and assign the corresponding value to it. Finally, return the populated result
object, representing the transformed data structure
function fromPairs(pairs) {
const result = {};
for (const [key, value] of pairs) {
result[key] = value;
}
return result;
}
This one can also be done by leveraging the JavaScript Object.fromEntries
. We can simply do the following
function fromPairs(pairs) {
return Object.fromEntries(pairs);
}