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

The error message "No native build was found for M2 MacBook" appeared while using npm with Node

I encountered this issue while working on my M2 MacBook, which ran smoothly on my older Intel MacBook. Any insights on what might be causing the problem? Using bun, but even running npm run dev (node 18) results in the same error. The same error has also ...

The access to the HTTP request has been restricted

Currently, I am developing multiple applications that need to communicate with each other. To test these apps, I am using both Chrome and Firefox browsers. Strangely, the issue persists in both browsers. The issue at hand: In one of my applications (let& ...

Tips on making an array readable by JavaScript using Jinja2 and Google App Engine

I'm currently facing an issue with transferring an array from a server to a web page through Jinja2 in Google App Engine. Despite my efforts, I'm struggling to make the array readable by my jQuery code. This is all new to me as it's my first ...

Iterating through the parsed JSON data in Ruby

Currently, I am working on iterating through a parsed JSON response retrieved from reddit's API. After conducting some research online, I have come across similar issues faced by others. However, none of the suggested solutions seem to resolve the pr ...

Sometimes, the `undefined` TypeError can unexpectedly pop up while making Ajax calls

Here is my issue with AJAX request and response: I have around 85 HTML pages that all use the same AJAX request. However, when working with these files, I sometimes encounter the following error. AJAX $(document).ready(function(){ localStorage.setIte ...

Unable to locate the element with the specified id: <path>

I am aiming to dynamically change the fill attribute of a specific <path> element when a page loads. Here is the detailed information about the path element: <path xmlns="http://www.w3.org/2000/svg" style="fill:#ff0000;stroke:#000000;stroke-wid ...

Displaying the output of a PHP script in an AJAX request

I am trying to display feedback from certain checks, like checking if a file already exists, after making an ajax call to upload a file using my script. However, for some reason, I can't get the response to show up. Why is the response not appearing? ...

Troubleshooting the issue with the default dropdown select in AngularJS

var jsonData ='[ {"type":"product", "id":1,"label":"Color", "placeholder":"Select Jean Color", "description":"", "defaultValue":"Brown", "choices":[{ "text":"Denim", "price":"$0.00", "isSel ...

Is it possible to utilize gulp to eliminate all require.js define([...]) wrappers throughout the codebase?

Is it possible to test my app without using require.js in order to assess the performance and file size if all files were concatenated into a single one? I'm contemplating using gulp to gather all *.js files in the app, running a gulp-replace to elim ...

Margin ambiguity in a vue.js application

I am facing an issue with my Vue.JS project setup. I want the App.vue to occupy the entire page and have different routes displayed within App.vue using router-view. But, when I try to add a margin to the content of my Game component, the margin seems to ...

Loop through a JSON object in C#

I am interested in creating a loop to validate a condition on my JSON object. I am searching for a method to iterate through the JSON object: JSON: {"tasks":[ { "id":-1, "name":"Gantt editor", "code":"", ...

The dictionary of parameters has an empty entry for the 'wantedids' parameter, which is of a non-nullable type 'System.Int32', in the 'System.Web.Mvc.JsonResult' method

The console is showing me an error stating that the parameters dictionary contains a null entry for parameter wantedids. I am trying to pass checked boxes to my controller using an array, so only the admin can check all boxes of tips for a specific user. T ...

An empty array is being returned by the Model.find() method after sorting

let query = Tour.find(JSON.parse(queryStr)); if (req.query.sort) { query = query.sort(req.query.sort);//a string 'ratings' } const tours = await query; res.status(200).json({ status: 'success', requestedAt: req.requestTime, ...

Steps to create a function in a .js file that uses ng-show conditions

I am in the process of validating a web page where the user inputs must be alphanumeric, have a maximum length of 45 characters, and be unique. Below is the code snippet I am working with. Is there a way to consolidate these three ng-show conditions into ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

How to send parameters through the Google Maps API URL using Vue.js

When using $router.push(), I receive two parameters: {{ this.$route.params.lat }} and {{ this.$route.params.lng }}, which are latitude and longitude coordinates. To access a Google Maps URL, I need to include both of these parameters: https://maps.googlea ...

Getting started with React Native project

Just dipping my toes into the world of React Native and looking for recommendations on the best starter kit/generator to kickstart my projects. Tried out "create-react-native-app" already, but curious if there are any other generators or kits out there tha ...

Guide on converting an entire request String into Json format on Android

My task is to send the following Json: {"method":"startSession", "params":["email" "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70151d11191c30151d11 2291e71">[email protected]</a>", "password" "1234", "stayLog ...

Show various columns in Select2

I am currently utilizing select2 and I am interested in displaying a multicolumn table as a dropdown. In order to achieve this, the width of the drop-down container should differ (be larger) than the input itself. Is it feasible to accomplish this? Furth ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...