'How can I obtain an object with the values as keys and vice versa - and with duplicate values stored in an array?
1. My task
In the object, how can I get an array in which the corresponding keys are stored if there are duplicate values in the input object?
const object5 = { a: 1, b: 2, c: 3, d: 1 };
const object6 = { a: 1, b: 1, c: 1, d: 1 };
/**
1. @param {object} ???
2. @returns {object} An object with the given object's values
as keys, and keys as values. If there are duplicate values in
the input object, the corresponding keys should be stored in
an array.
*/
2. Tests
console.log(swapPairs3(object5))// , { 1: ["a", "d"], 2: "b", 3: "c" }; console.log(swapPairs3(object6))// , { 1: ["a", "b", "c", "d"] };
Solution 1:[1]
You can reduce the entries of the object using Array.prototype.reduce.
const groupByValue = (obj) =>
Object.entries(obj).reduce((r, [k, v]) => ((r[v] ??= []).push(k), r), {});
console.log(groupByValue({ a: 0, b: 0, c: 3, d: 1 }));
console.log(groupByValue({ a: 1, b: 1, c: 1, d: 1 }));
A more comprehensive version of the above solution:
function groupByValue(obj) {
return Object.entries(obj).reduce((r, [k, v]) => {
r[v] = r[v] ?? [];
r[v].push(k);
return r;
}, {});
}
console.log(groupByValue({ a: 1, b: 2, c: 3, d: 1 }));
console.log(groupByValue({ a: 1, b: 1, c: 1, d: 1 }));
Documentation: Nullish Coalescing Operator (??)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
