Is there a way to find keys with matching values within a dictionary?

In my dictionary, I have two sets of identical array values for different keys. My query is: How can I determine which keys have the same value based on inputting just one value? I want to retrieve all keys that share the same values as an output. This is important for my project where I can only use either sharp or flat, not both, in detecting a note.

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

Answer №1

Is this example similar to what you're looking for?

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)

Answer №2

To solve this problem, you can utilize methods such as Array.filter, Array.every, Array.some, and Array.includes in the following manner:

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

const entries = Object.entries(data)
const duplicates = entries.filter(([key1, value1]) => value1.every(value => entries.some(([key2, value2]) => key1 != key2 && value2.includes(value))))
const output = duplicates.reduce((accumulator, [key, value]) => (accumulator[key] = value, accumulator), {})

console.log(output)

The concept here is to extract the values of each key, filter them so that each value is present in the values of other keys in the object.

Alternatively, you can obtain an array of keys with similar values using Array.reduce and Array.filter:

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

const output = Object.entries(data).reduce((result, [key, value], index, array) => {
  let combinedValue = value.join('-')
  result[combinedValue] = [...result[combinedValue] || [], key]
  return index == array.length-1 ? Object.values(result).filter(array => array.length > 1) : result
}, {})

console.log(...output)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing empty arguments with `execute_script` in Selenium with Firefox

I need help setting the value of a textarea using JavaScript instead of the send_keys() method. According to the documentation, I should be able to pass a webelement to execute_script as a parameter and refer to this parameter using the arguments array. H ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

XMLHttp request experiencing mixed content issues

Struggling with obtaining OAuth Tokens from a POST request through the Bungie API using javascript and XMLHttpRequest. Despite both my website and the API endpoint being secure (https), every post request I send returns a Mixed Content page error. I'v ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Experiencing difficulties with node and asynchronous programming

I'm attempting to use async-waterfall in order to fetch data from an API, save it as JSON, and then store it in a database. Here is a snippet of the code I have so far. Can someone assist me with this process? async.waterfall([ function getBo ...

Mapping values to keys in PHP arrays

Within my code, I am working with the following array: params { [0] => { name => "xxx" value => "yyy" } [1] => { name => "uuu" value => "vvv" } } The desired outcome for this array is as follows: params { [ ...

Remove array element by key (not numerical index but string key)

Here is a JavaScript array that I am working with: [#ad: Array[0]] #ad: Array[0] #image_upload: Array[0] 13b7afb8b11644e17569bd2efb571b10: "This is an error" 69553926a7783c27f7c18eff55cbd429: "Yet another error" ...

Retrieving information from a Rowdatapacket with expressjs

Is there a way to use a loop to retrieve a single value from each row in RowDataPacket? Currently, my results look like this: [ RowDataPacket { id: 522, number: '111', test: 'testing' }, RowDataPacket { id: 523, number: '112' ...

What is the process for submitting a form in Laravel 5 with ajax?

Struggling with understanding how to create an ajax post in Laravel. I would like to display errors using jQuery after validation, but I'm unsure about accessing the object sent to my controller and what needs to be 'returned' in the control ...

Incorporating Chakra UI, what is the best way to display a modal box upon page load?

Is there a way to display a modal box when the page loads in Chakra UI? I have been searching through Chakra's documentation but couldn't find any information on this. import { useDisclosure, Modal, ModalOverlay, ModalContent, ...

How did my attempt to add a length() method to Object end up breaking jQuery?

Here is the code I created: Object.prototype.length = function(){ var count = -1; for(var i in this) count++; return count; } Surprisingly, when viewing my page with Firebug enabled, it gives an error stating that jQuery's .appendTo() is ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

The data type 'StaticImageData' cannot be converted to type 'string'

I've hit a roadblock with interfaces while working on my NextJS and TypeScript project. I thought I had everything figured out, but I'm encountering an issue with the src prop in my Header component. The error messages I keep receiving are: Typ ...

Why isn't the nested intricate directive being executed?

After watching a tutorial on YouTube by John Lindquist from egghead.io, where he discussed directives as components and containers, I decided to implement a similar structure but with a more dynamic approach. In his example, it looked something like this ...

Create a vibrant PNG image background that changes dynamically based on the dominant color of the

Is it possible to dynamically set the background color of a PNG image, either white or black, based on the dominant color in the image? For example, this image should have a dark background: https://i.stack.imgur.com/cerjn.png And this one should have a ...

deployJava.js injects a new <embed> element into the header section of the webpage

I've ran into an issue with the Java applets on my website. I included the deployJava.js load tag in the head section of the page, but when I look at the resulting HTML in Chrome debugger, this script seems to be breaking my head content and starting ...

Unset the class upon clicking outside the div, but maintain the class unset when the div is closed

I have a div that opens when the question mark icon in the upper right corner of the document is clicked. When clicked, a class is added which transforms the question mark into a close icon. When clicking outside the div, the div closes and the class is re ...

List of random points generated using Three.js

Novice inquiry: I have generated some random points in JavaScript. How can I individually access each point later on? I remember something about an 'Object' that holds all the points, allowing me to manipulate their positions or selectively retri ...

AngularJS Data Binding Issue - Watch cycle fails to trigger

View the JSFiddle example here: https://jsfiddle.net/pmgq00fm/1/ I am trying to achieve real-time updating of my NVD3 chart by utilizing the setInterval() function on line 39, which updates the data bound to the directive. Here is a brief overview of the ...

Having difficulty uploading a file using a formGroup

Currently, I am using Angular to create a registration form that includes information such as name, email, password, and avatar. For the backend, I am utilizing NodeJS and MongoDB to store this information. I have successfully written the registration API ...