Discover discrepancies (including additional elements) within n sets of objects

In my current project, I am working with an array named props which consists of multiple arrays containing objects. Each object within these arrays has four properties: participation_enabled, name, pathing_enabled, and id. These properties can have varying values across different arrays.

My main objectives are twofold:
1) Identify all the object properties that differ among the arrays and store them in a separate array called diffs;
2) Find any extra objects (unique id) that do not exist in other arrays and store them in an array named extra.

While my code successfully captures the differences, it currently falls short in identifying all the extra objects...

For instance, consider the following example:

[
  [
    {participation_enabled:"false", name:"PropEins", pathing_enabled:"true", id:"prop1"}, 
    {participation_enabled:"false", name:"User Status", pathing_enabled:"false", id:"prop2"}, 
    {participation_enabled:"false", name:"Initial ID", pathing_enabled:"false", id:"prop3"}, 
    {participation_enabled:"false", name:"User ID", pathing_enabled:"false", id:"prop4"}, 
    {participation_enabled:"false", name:"Subdomain3", pathing_enabled:"false", id:"prop20"},
    {participation_enabled:"false", name:"Subdomain4", pathing_enabled:"false", id:"prop21"},
    {participation_enabled:"false", name:"Subdomain5", pathing_enabled:"false", id:"prop22"}
  ], 
  ...
]

The resulting diffs array from this example should include:

[
  ...
]

Additionally, the extra array should capture:

[
  ...
]

This excerpt features my original implementation code:

  
...

Answer №1

I have successfully implemented and tested the following solution:

var data = [
  [
    {enabled:"false", title:"PropOne", tracking_enabled:"true", id:"prop1"}, 
    {enabled:"false", title:"User Status", tracking_enabled:"false", id:"prop2"}, 
    {enabled:"false", title:"Initial ID", tracking_enabled:"false", id:"prop3"}, 
    {enabled:"false", title:"User ID", tracking_enabled:"false", id:"prop4"}, 
    {enabled:"false", title:"Subdomain3", tracking_enabled:"false", id:"prop20"},
    {enabled:"false", title:"Subdomain4", tracking_enabled:"false", id:"prop21"},
    {enabled:"false", title:"Subdomain5", tracking_enabled:"false", id:"prop22"}
  ], 
  [
    {enabled:"false", title:"PropOne", tracking_enabled:"false", id:"prop1"}, 
    {enabled:"false", title:"Room", tracking_enabled:"false", id:"prop2"}, 
    {enabled:"false", title:"Domain", tracking_enabled:"false", id:"prop70"}
  ], 
  [
    {enabled:"true", title:"PropOne", tracking_enabled:"true", id:"prop1"}, 
    {enabled:"true", title:"User Status", tracking_enabled:"true", id:"prop2"}, 
    {enabled:"true", title:"Tracking Code", tracking_enabled:"true", id:"prop3"}, 
    {enabled:"false", title:"User ID", tracking_enabled:"true", id:"prop4"}, 
    {enabled:"false", title:"User ID2", tracking_enabled:"false", id:"prop50"}
  ]
];
  var diffData = {};
  var extraItems = [];
  var itemIds = [];
  var uniqueKeys = [];
  
  data.forEach(function(item){
    item.forEach(function(element) {
      itemIds.push(element.id);
    });
  })
  itemIds.filter(function(a){
    if(itemIds.indexOf(a) == itemIds.lastIndexOf(a)) {
      uniqueKeys.push(a);
    }
  });
  data.forEach(function(item){
    item.forEach(function(element){
      if(uniqueKeys.indexOf(element.id) >= 0) {
        
        extraItems.push(element);
      }    
    });
  });
  
  data.forEach(function(item, i){
    if (i == 0) {
      item.forEach(function(element, ind){
        diffData[element.id] = {};
        diffData[element.id].index = [ind];
        for (var key in element) {
          diffData[element.id][key] = [element[key]];
        }
      });
    }
    else {
      item.forEach(function(element){
        var itemId = element.id;
        for (var key in element) {
          if(diffData[itemId]) {
            diffData[itemId][key].push(element[key]);
          }
        }
      });
    }
  });
  
  for (var key in diffData) {
    var nestedItem = diffData[key];
    var indexValue = nestedItem.index.pop();
    for (nestedKey in nestedItem) {
      nestedItem[nestedKey] =  _.filter(nestedItem[nestedKey], function(item, pos) {
        return nestedItem[nestedKey].indexOf(item) == pos;
      });
      
      if (nestedItem[nestedKey].length < 2) {delete nestedItem[nestedKey];}
      
    }
    diffData[key].id = key;
    diffData[key].index = indexValue
    if (_.keys(diffData[key]).length < 3) {delete diffData[key];}
  }
  
  diffData = _.values(diffData);
  console.log("extra items:", extraItems);
  console.log("different values:", diffData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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

1. "The Three.js ball"2

Looking at this snippet of code: mesh = new THREE.Mesh(new THREE.SphereGeometry(500,60,40), new THREE.MeshBasicMaterial({map:texture,overdraw:true})); Can you explain the significance of the values 60 and 40 in relation to the sphere? mesh.sc ...

Initializing arrays at the class scope in C++11

Having experience with Java and Ruby, I find coding simple tasks in C++ to be more challenging... I am looking to initialize an array in the constructor of a class with predetermined values that can be accessible to all methods within the class. It's ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

Why are NodeJS and Jade/Pug variables not being recognized in the Jade script?

After successfully passing a variable to Jade like #{myvar}, I encountered an issue when trying to access it in a script block. Despite using typeof(myvar) and confirming that it was initially undefined, my attempts to display its value within the script b ...

Can each `InstancedBufferGeometry` instance have its own set of unique vertex colors?

Is it possible to assign different vertex colors to each instance of InstancedBufferGeometry? const xRes = 3; const yRes = 2; const numVertices = xRes * yRes; geometry = new THREE.InstancedBufferGeometry(); geometry.copy(new THREE.PlaneBufferGeometry(3, 2 ...

Having trouble assigning a value to the datapicker through the onchange event and the name attribute in the code below

const stateValues = { code: '', product: '', checked: 'false', jobCardNo: '', openDate: '', completionDate: '', serial: '', technicalNo: '', ...

Strange findings in JSONArray

While attempting to retrieve data from another Java class using JSONArrays and JSONObjects, I encountered unexpected results. In my Info.java class, the code looks like this: public JSONArray getSpawnedPets() { JSONArray petsArray = new JSONArray(); ...

Traverse the NSArray of items lacking identifiers in Objective C

My NSArray is structured like this: [{ "Id":"456", "Type":"Dog", "Sound":"Bark", }, { "Id":"789", "Type":"Cat", "Sound":"Meow", }] I attempted the following: for (id key in array) { // This approach did not work NSLog(@"%@", key[@"Ty ...

Use the ng-pattern regex to specifically identify instances where a pattern occurs only once

Looking for a string pattern 'abcd' followed by a colon(:) and any number of integers, with the restriction that this pattern cannot be repeated. Here are some examples of valid patterns: - abcd:23415 - abcd:23 And invalid patterns: - asda:4 ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

Make sure to wait for the current operation to finish before moving onto the next one

In the primeData function within the datacontext, four queries are made to a back-end Web API service: function primeData(forceRefresh) { return (getLookups(forceRefresh) // this needs to complete before moving on .then(success)) ...

Update the picture displayed in the parent div when it is in an

My code currently changes the image when a parent div is in an active state, but I'm struggling to figure out how to revert it back to the original image when clicked again. I attempted to use 'return false' at the end of the script, but it ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

javascript converting a string into a variable

I have a JSON string coming from an ajax call and I want to assign a value to a predefined variable: var predefined = "hello world"; var foo = {"msg":"predefined"}; // The JSON string I need to display the standard text by accessing it like this: alert( ...

What is the best way to integrate the Firestore SDK into an Oracle JET project?

Short Version: How can I integrate Google Cloud Firestore into an Oracle Jet project? I'm working on incorporating the Firestore client SDK into my Oracle JET project. I've executed the following command to add the package to my project: npm ins ...

JavaScript transforming an array into a counter

I am seeking a way to transform a one-dimensional array into a frequency dictionary in JavaScript. The array elements should serve as keys, while their frequencies act as values. Take, for example, the Python script below, which generate a list of 1024 ra ...

When the parent div contains at least four divs, show the scroll arrow containers

In my code, there is a parent div that holds multiple child divs. If the number of child divs within the parent div exceeds 4, I want to show the scroll arrow containers. If it's less than 4, then those arrow containers should not be displayed. The ...

Exploring the Depths of Vue Router: Incorporating Dynamic Nested Routes

Hey everyone, I'm currently diving into working with the vue-router and Vuex Store. I'm facing a challenge where I have a route that consists of two dynamic parameters (:id, :templateId). My question is, what do I need to specify in my routes c ...

Activate the event when the radio button is changed

Is there a way to change the selected radio button in a radio group that is generated using a for loop? I am attempting to utilize the changeRadio function to select and trigger the change of the radio button based on a specific value. <mat-radio-group ...