Utilize lodash to locate the key of an object with deeply duplicated values

Looking at the object provided below:

var data = {
        2: [[1,2],[3,4,5],[6,7]],
        3: [[1,2],[3,4],[6,7]],
        4: [[1,2],[3,4,5],[6,7]],
        5: [[10,2],[3,4,5],[60,7]]
    }

I am interested in retrieving the key 2 from the object as its value appears multiple times in the array. There could be other keys with duplicate values as well.

Using lodash, I attempted the following method but was unsuccessful. I am unsure about how to proceed:

var dups = [];
_.map(formData,function(key, value){
    dups.push(value);
})
var duplicateArray = _.uniqWith(dups, _.isEqual);

Answer №1

This particular piece of code is designed to match the entire array regardless of the value sequence and count. Take a look at the example below

// Insert your code here

Plunker: https://plnkr.co/edit/6jEByZHQhcwUopqqG4a2?p=preview (Click on the link above and open the console to view the result)

The output will be ["2","3"] because "2" matches "4" and "3" matches "6".

// Insert your code here

var data = {
  2: [ [1, 2], [3, 4, 5], [6, 7]],
  3: [[1, 2],[3, 4],[6, 7]],
  4: [[2, 1, 2, 1],[5, 3, 4],[6, 7]],
  5: [[10, 2],[3, 4, 5],[60, 7]],
  6: [[2, 1],[3, 4],[7, 6, 6]]
}

var dups = [];

//sorted and unique buffer.
var buff = _.clone(data);
_.forEach(buff, function(lvl1, key) {
  buff[key] = _.map(lvl1, function(val) {
    return _.uniq(_.sortBy(val));
  });
});

_.forEach(buff, function(lvl1, key) {

  //Matching each row with all others.
  //e.g. 2 with 3, 2 with 4, 2 with 5 ..... 6 with 5.
  _.forEach(buff, function(_lvl1, _key) {
    //Skipping entries like 2 with 2, 3 with 3 and so on
    if (key !== _key) {
      console.log('compare ' + key + ' with ' + _key);
      var x = _.filter(_lvl1, function(val, index) {
              //Conditions below are only true because arrays are sorted and unique.
              //Both must be of the same length 
        return val.length === lvl1[index].length
               //Length of intersection of both values must be exactly equal 
               && _.intersection(val, lvl1[index]).length === val.length;
      });
      //If count matches and key and _key are not in dups
      // key and _key not in dups because we only want the following:
      // 2 with 4 -> 2
      // 4 with 2 -> ignore! (we don't want to include 4)
      //I hope this makes sense
      if (x.length === _lvl1.length && _.indexOf(dups, key) === -1 && _.indexOf(dups, _key) === -1) {
         //Mark the key as duplicate
         dups.push(key);
      }
    }

  });
});


console.log(dups)

I trust this explanation is helpful!

Answer №2

Not entirely certain if I understand your question correctly, but based on my interpretation, the answer might resemble something like this: (sample):

Javascript:

  var data = {
        2: [[1,2],[3,4,5],[6,7]],
        3: [[1,2],[3,4],[6,7]],
        4: [[1,2],[3,4,5],[6,7]],
        5: [[10,2],[3,4,5],[60,7]]
    };

  var find = function(input){
    var res = [];
    for(var prop in input){

      var start = false;
      for(var prop2 in input){
        if(start){
          var flag = JSON.stringify(input[prop]) == JSON.stringify(input[prop2]);
          if(flag){
            var flag3 = true;
            for(var j = 0; j < res.length; j++)
              if(JSON.stringify(input[prop]) == JSON.stringify(input[res[j]])){
                  flag3 = false
                  break;
              }
            if(flag3)
              res.push(prop);
            break;
          }
        }
        else{
         if(prop == prop2)
          start = true; 
        }
      }

    }
    return res;
  }

  var answer = find(data);

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

Revolutionary custom binding with Bootstrap popover integration

Utilizing asp.net mvc with dynamic knockout columns, I am facing an issue with one of the column headers named "Status". The desired functionality includes a bootstrap popover that displays information when a user clicks a font-icon question mark. Here is ...

Transfer elements from collections employing multer

Data Payload Example:- education[0][university]: jru education[0][degree]: mca education[0][specialization]: computer application education[0][certificate_pdf_url]: (binary) education[0][degree_type]: Teaching Degree education[0][years_of_study]: [&q ...

Is it possible to create a component in React without using JSX?

Is it possible to create a React component without using JSX? I'm trying to render a header element with nested h1 and h2 tags, but only the paragraph tag is showing up. Why is only the React element rendering and not the rest? I referred to a Codepe ...

Is it possible to utilize window.location.replace function within an iframe?

Is it possible to use window.location.replace to bypass history and target on-page anchors without page reloads, but encounter issues when working within iframes? The main problem seems to be a CSP (content security policy) violation for script-src ' ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...

React: Remove a particular row from the table

I am currently working on a project that involves building a table component. Each row in this table is also a separate component. class FormulaBuilder extends Component { constructor(props) { super(props); this.state = ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

How about generating a promise that serves no real purpose and simply resolves?

Managing promises in Node.js can be a bit tricky, especially when dealing with different scenarios. One common use case is catching the last promise result and formatting it accordingly. req.resolve = (promise) => { return promise.then(() => { ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

Combining two arrays of objects using JavaScript

I am working with two arrays of objects that look like this: objects [ { countMedias: 2 }, { countMedias: 1 }, { countMedias: 3 }, { countMedias: 1 }, { countMedias: 2 } ] listePlayliste [ { nom_playlist: 'bbbb' }, { nom_playlist: &apo ...

Obtain the view property access while invoking render function as a callback

When working with the guid variable in the render() function, I encountered a limitation where I could only pass it to the constructor. Here is an example of the code I used: app.views.CompanyView = Backbone.View.extend({ el: '#company-view' ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...

The Bootstrap modal form fails to properly handle the POST method when sending data to the server

I am encountering an issue with a button that triggers a modal form <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Add Material</a> The modal appears as shown below: https://i.stack.imgur.com/J39x9.pn ...

Control three.js camera rotation based on the movement of a mobile device within a specified div element

Is there a way to incorporate mobile device movement control for camera rotation in this demo along with the current mouse movement control? The camera rotation has been set up for mobile here, but not in conjunction with mouse movement. The following code ...

Exploring Vue Slots: A guide to parsing and rendering slot components

Currently facing a challenge while developing a web page using Vue, specifically with parsing and rendering the child components inside the <slot>. I need to extract the slot content, convert it into an array of components, and display these compo ...

Accessing a webpage solely by logging in prevents unauthorized access

My login page currently redirects to a page named gallery.html upon successful login. However, I have noticed that entering /gallery.html in the URL also directly accesses the secure page without logging in. Can anyone suggest an effective way to impleme ...

Click on the input field to automatically choose files or folders

I am currently working on a project where I am using a combination of javascript and html to dynamically load a file in the browser. Here is what my code looks like: <input type="file" id="file-input" @input="openFile" /&g ...

Discovering the source DOM element that initiated ng-change

I am currently working with angularJS and have multiple <select> elements on my webpage, each with its own ng-change function. Here is an example: <select id="hairColorComponent" ng-model="hairColor" ng-options="option.name for option in ...