Вот еще одна реализация, основанная на Array.reduce
:
const o = { 1: 'cat', 2: 'dog', 3: 'cat' }
const result = Object.entries(o).reduce((r, [k,v], idx, arr) => {
r[v] = [...(r[v] || []), { [k]: v }]
return idx == arr.length-1 ? Object.values(r).find(x => x.length > 1)[0] : r
}, {})
console.log(result)
Здесь он разбит с более подробной информацией:
const object = { 1: 'cat', 2: 'dog', 3: 'cat' }
const result =
Object.entries(object) // get object key & value in the form of [key,value]
.reduce((accumulator, [k,v], index, array) => { // start an `Array.reduce`
// create the grouping on the value `cat`/`dog`
accumulator[v] = [...(accumulator[v] || []), { [k]: v }]
if(index == array.length-1) // if we are at the end of the `Array.reduce`
// Return the values of the accumulator filtered by the arrays which length is more than 1
// and take from that array the initial element
return Object.values(accumulator).find(x => x.length > 1)[0]
else // Not at the end keep returning the accumulator
return accumulator
}, {})
console.log(result)