What is the best way to combine JavaScript objects with identical values?

We have a task to compare each input key with others to find any common values. If there are common values, we need to concatenate them together and display the pairs. If no common values are found, then an empty array should be displayed as output.

input : 
{
    "harsh" : ["cricket", "vollyball"],
    "aasim" : ["cricket", "football", "ludo", "COD", "rugb", "vollyball", "Racing"],
    "jignesh" : ["cycling", "cricket"],
    "jimish" : ["cycling"],
    "prince" : ["vollyball","football"],
    "raj" : ["ludo","cricket","cycling"]
}

output : 

{
    "harsh, aasim":["cricket","vollyball"],
    "harsh, jignesh":["cricket"],
    "harsh, jimish":[],
    "harsh, prince":["vollyball"],
    "harsh, raj":["cricket"],
    "aasim, jignesh": ["cricket"],
    "aasim, jimish": [],
    "aasim, prince": ["vollyball","football"],
    "aasim, raj": ["ludo","cricket"],
    "jignesh, jimish" : ["cycling"],
    "jignesh, prince" : [],
    "jignesh, raj" :["cycling"],
    "prince, raj" : []
    
}

Answer №1

Take a look at this code snippet:

const findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) !== index);
    
const rearrangeObject = providedObj => {
     const newObj = {};
     const keys = Object.keys(providedObj);
    
      for (let i = 0; i < keys.length; i++) {
          for (let j = i + 1; j < keys.length; j++) {
              let str = keys[i] + ", " + keys[j];
              newObj[str] = findDuplicates([...providedObj[keys[i]], ...providedObj[keys[j]]);
          }
      }
      return newObj;
}
    
const providedObj = {
      "harsh": ["cricket", "volleyball"],
      "aasim": ["cricket", "football", "ludo", "COD", "rugby", "volleyball", "Racing"],
      "jignesh": ["cycling", "cricket"],
      "jimish": ["cycling"],
      "prince": ["volleyball", "football"],
      "raj": ["ludo", "cricket", "cycling"]
};
console.log(rearrangeObject(providedObj));

Answer №2

Here is a PHP solution for achieving the desired result, although if the provided code works for you, that's perfectly fine:

  var name = [
        "harsh",
        "aasim",
        "jignesh",
        "jimish",
        "prince",
        "raj"
    ]
    var array1 = [
        ["cricket", "vollyball"],
        ["cricket", "football", "ludo", "COD", "rugb", "vollyball", "Racing"],
        ["cycling", "cricket"],
        ["cycling"],
        ["vollyball", "football"],
        ["ludo", "cricket", "cycling"]
    ];
    //array1= console.log(array1);
    array = [];
    for (var i = 0; i < array1.length; i++) {

        for (var k = 1; k < array1.length; k++) {
            var array5 = array1[i].filter(function(obj) {
                return array1[k].indexOf(obj) == -1;
            });
            
            if(array5.length!=0){
            array[name[i]] = array5
            
            }

        }
    }

    console.log(array);

Answer №3

const data = {
    "samantha" : ["basketball", "tennis", "swimming"],
    "michael" : ["golf", "basketball", "baseball"],
    ""ryan" : ["cycling", "tennis"],
    "lisa" : ["cycling"]
};

const dataKeys = Object.keys(data);
const keyPairs = [];
while (dataKeys.length) {
  const k0 = dataKeys.shift();
  dataKeys.forEach(k1 => keyPairs.push([k0, k1]));
}
const result = {};
keyPairs.forEach(k => result[k.join(', ')] = data[k[0]].filter(k0 => data[k[1]].includes(k0)));
console.log(result);

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

Having trouble with my bootstrap slider carousel - it's just not cooperating

I incorporated Bootstrap's carousel to display the various courses on my website, featuring three courses at a time before transitioning to the next set of three. However, I am encountering an issue with this setup. Please see the image below for refe ...

Two-way data bindings trigger the digest() function to iterate 10 times

I'm facing issues with angular binding and my experience level in this area is limited. I will be posting all related questions here. I have a piece of angularjs code that is triggering 10 digest() cycle reached errors. After researching similar posts ...

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

Using AngularJS to update text content retrieved from a file and display it in a textarea

Is there a way to create a textarea using AngularJS that can be populated either by typing, entering a URL, or uploading a plain text file? While I am able to load the file content into the variable linked to the textarea, I'm facing an issue where ge ...

The initial button click does not display data

I am currently facing an issue with my app when trying to display JSON data retrieved from a PHP web service. The problem occurs when I click the fetch button for the first time and the data does not show up on the labels. After debugging, I noticed that ...

Numerous checkboxes have been chosen alongside a submission button

I recently completed a small project involving multiple checkboxes using ajax. You can view the demo here. However, I am now looking to implement a submit button for filtering options. After selecting multiple checkboxes and clicking the submit button, onl ...

How does gray-matter function in Node.js affect the matter within?

import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; const postsDirectory = path.join(process.cwd(), 'posts'); // ... ... ... // export function getPostData(id) { const fullPath = ...

How can the WP JSON REST API by Ryan McCue be used to search for posts with particular meta data using the 'AND' relationship?

I am using the Wp_query class to fetch posts in a template. Initially, 15 posts are loaded on page load and can be filtered successfully. I then use Infinity scroll to retrieve additional posts utilizing JSON restful services. While the server-side filteri ...

Automatic popup updates when submitting a form in a Chrome extension

Looking to develop a chrome extension popup window that, when clicked, will present a form for users to input their name and college. The goal is to save this data in chrome storage and then replace the popup with a new window displaying a greeting message ...

Steps to set up datetimepicker with varying date ranges for several input fields

I am having trouble getting a new date range for each text box in my form. It seems to only return the date range from the last textbox, even though I have made the textbox IDs dynamic. I have both start and end dates for each textbox and I have calculated ...

Expanding a Node.js class to incorporate additional static class elements

I have a query where I believe that extending a class might be the solution, but I am not entirely sure. Here is the scenario... There is a class defined as follows: class Field { apiName; /** * Creates an instance of Field with the given par ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

Meteor, enhanced with the dynamic Iron Router module and integrated

I am working on a project using Meteor (Meteor.com) and I want to incorporate iron-router for the page routing along with the pre-existing accounts-ui package for login functionality. Previously, my {{loginButtons}} functioned properly, but ever since I i ...

Tips for displaying a sub-menu upon hovering

I am attempting to display the list of sub-menu items when hovering over the main menu item. I have tried using the following CSS code, but it did not work as expected. Any assistance will be greatly appreciated. CSS: summary.header__menu-item.list-menu__ ...

Steps to insert an image object into a table

Note: The image in the database is named "profileImage." I want to create a dynamic image object similar to other objects when I insert this code. { label: "Image", name: "profileImage", } It will display the image endpoint as 3704545668418.PNG and ...

Accessing variables within the controller's scope

Here is the JSON data I'm working with: { "id": "026001", "description": "Drop Forged Double Coupler", "CASHCUST01": { "hireRate": "0.01500", "saleRate": "2.50000" }, "SMITH00010": { "hireRate": "0.02500", "saleRate": "1.50000" }, " ...

Achieving stylish CSS effects on dynamically loaded content post AJAX request

I am currently developing an application that utilizes AJAX to fetch JSON data and then uses an ES6 template literal to construct the view. It's a simple demonstration: let mountPoint = document.getElementById("mountPoint"); let view = document.cre ...

Having Trouble with QR Code Generator Functionality

UPDATE: The initial code has been updated to implement the recommendations provided. I am currently working on a QR Code generator that updates every minute. Although I have developed the code below, I am encountering some errors and could use some assist ...

Stop jquery and/or x-editable from automatically converting strings into objects

I am facing an issue where I want to display a JSON string using x-editable, but it is converting it into an object against my wishes. This results in [object Object] being displayed instead of the actual string. How can I prevent this from happening? var ...

Transfer data from JSON column in DataFrame to individual rows in the DataFrame

Encountering a dilemma that needs resolution. Among my assets is a JSON file featuring nested dictionaries in one of its columns. To bring this JSON data into a DataFrame, I utilize the following code: df2=pd.read_json(filename) The resulting DataFrame co ...