Skip to content Skip to sidebar Skip to footer

How To Obtain Different Keys Which Have Same Values In A Dictionary?

I have a dictionary like this one and as you can see, I have two identical array values for two different keys. My question is: how can I get these two keys by giving in input one

Solution 1:

Something like this?

var dictionary = {
  "Cmaj7": ["C","E","G","B"] ,     //majors"C#maj7": ["C#","F","G#","C"],
  "Dbmaj7":["C#","F","G#","C"]}
  
var newObj = {}
for (var o in dictionary) {
  var reverseKey = dictionary[o].join("_");
  if (!newObj[reverseKey]) newObj[reverseKey]=[];
  newObj[reverseKey].push(o);
}
console.log(newObj)

Solution 2:

You can solve this via Array.filter,Array.every, Array.some and Array.includes like this:

var data = { "Cmaj7": ["C", "E", "G", "B"], "C#maj7": ["C#", "F", "G#", "C"], "Dbmaj7": ["C#", "F", "G#", "C"] }

const e = Object.entries(data)
const dubs = e.filter(([k1, v1]) => v1.every(v => e.some(([k2, v2]) => k1 != k2 && v2.includes(v))))
const result = dubs.reduce((acc,[k,v]) => (acc[k] = v, acc), {})

console.log(result)

The idea is to get the values of each key and filter then so that every one of the values are included in the rest of the object values.

You can also just get an array of the keys with same values via Array.reduce and Array.filter:

var data = { "Cmaj7": ["C", "E", "G", "B"], "C#maj7": ["C#", "F", "G#", "C"], "Dbmaj7": ["C#", "F", "G#", "C"] }

const result = Object.entries(data).reduce((r, [k,v], i, a) => {
  let key = v.join('-')
  r[key] = [...r[key] || [], k]
  return i == a.length-1 ? Object.values(r).filter(a => a.length > 1) : r
}, {})

console.log(...result)

Post a Comment for "How To Obtain Different Keys Which Have Same Values In A Dictionary?"