Discover identical values within an array of objects and consolidate certain duplicate keys and values

I have two lists of items

list1 = [
 {
  "id_0":356,
  "name":"India",
  "key1":150
 },
 {
  "id_0":356,
  "name":"India",
  "key2":200
 },
 {
  "id_0":748,
  "name":"Swaziland",
  "key1":140
 },
 {
  "id_0":748,
  "name":"Swaziland",
  "key2":180
 }
]

I am attempting to identify the matching id_0 in the list and combine the duplicate item's key2 and its value.

The desired outcome is as follows:

list1 = [
 {
  "id_0":356,
  "name":"India",
  "key1":150,
  "key2":200
 },
 {
  "id_0":748,
  "name":"Swaziland",
  "key1":140,
  "key2":180
 }
]

What is the process to locate the duplicate value and merge the repeated key-value pair in the list?

Answer №1

To streamline your array, employ the Array.prototype.reduce() method.

Combine duplicate items by utilizing Object.assign().

var data = [
    { 'id_1': 789, 'title': 'USA', 'value1': 300 },
    { 'id_1': 789, 'title': 'USA', 'value2': 400 }
];

var outcome = data.reduce(function(previous, element) {
    var newElement = previous.find(function(i) {
        return i.id_1 === element.id_1; 
    });
    if (newElement) {
        Object.assign(newElement, element);
    } else {
        previous.push(element);
    }
    return previous;
}, []);

console.log(outcome);

If Object.assign from ES6 is not functioning properly, you can substitute it with:

for (var property in element) {
    newElement[property] = element[property];
};

Answer №2

Check out this JSFiddle link

var array = [
 {
  "id_0":356,
  "name":"India",
  "key1":150
 },
 {
  "id_0":356,
  "name":"India",
  "key2":200
 },
 {
  "id_0":356,
  "name2":"china",
  "key2":200
 }
]

function mergeArray( arr )
{
   var outputObj = {};
   for ( var counter = 0; counter < arr.length; counter++ )
   {
      var obj = arr[ counter ];
      for( var key in obj )
      {
         if ( !outputObj[ key ] )
         {
           outputObj[ key ] = obj[ key ];
         }
      }
   }
   return outputObj;
}
console.log( mergeArray( array ) );

For an 'UPDATED' version, click on this updated fiddle link

var array = [
 {
  "id_0":356,
  "name":"India",
  "key1":150
 },
 {
  "id_0":356,
  "name":"India",
  "key2":200
 },
 {
  "id_0":400,
  "name2":"china",
  "key2":200
 },
 {
  "id_0":400,
  "name2":"china",
  "key2":200
 }
]
function mergeArray( arr )
{
   var outputObj = {};
   for ( var counter = 0; counter < arr.length; counter++ )
   {
      var obj = arr[ counter ];
      for( var key in obj )
      {
         if ( !outputObj[ key ] )
         {
           outputObj[ key ] = obj[ key ];
         }
      }
   }
   return outputObj;
}

function collateArray( arr )
{
   var outputObj = {};
   var result = [];
   for ( var counter = 0; counter < arr.length; counter++ )
   {
      var obj = arr[ counter ];
      var id_0value = obj[ "id_0" ];
      if ( !outputObj[ id_0value ] )
      {
        outputObj[ id_0value ] = [];
      }
      outputObj[ id_0value ].push( obj );
   }
   console.log( outputObj );
   for ( var key in outputObj )
   {
      result.push( mergeArray( outputObj[ key ] ) );
   }
   return result;

}
console.log( collateArray( array ) );

Answer №3

To achieve a time complexity of O(n), using a temporary Object as a map to store key => item is recommended:

var arr = [
 {
  "id_0":356,
  "name":"India",
  "key1":150
 },
 {
  "id_0":356,
  "name":"India",
  "key2":200
 },
 {
  "id_0":748,
  "name":"Swaziland",
  "key1":140
 },
 {
  "id_0":748,
  "name":"Swaziland",
  "key2":180
 }
];

// items:            the array to be merged into unique values.
// attrName:    the attribute's name used for distinguishing items.
// isOverwrite:Determines if values should be overwritten by later ones or not. Default is false.
function getUnique(items, attrName, isOverwrite) {
  // Map to store objects based on their id.
  var store = {};
  // Array to hold the result.
  var result = [];
  
  isOverwrite = !!isOverwrite;
  
  items.forEach(function(item) {
    var id = item[attrName];
    var key;
    
    // Check if item already exists in store.
    var target = store[id];
    
    // If item exists in store, merge it with existing one.
    if (typeof target !== 'undefined') {
      for (key in item) {
        if (!item.hasOwnProperty(key)) {
          continue;
        }
        
        // Use newest value if isOverwrite is true, apply only new values otherwise.
        if (isOverwrite || typeof target[key] === 'undefined') {
          target[key] = item[key];
        }
      }
    } else {
      // If item is not in store yet, clone it and put in result array and map for reference.
      var clone = {};
      for (key in item) {
        if (item.hasOwnProperty(key)) {
          clone[key] = item[key];
        }        
      }
      store[id] = clone;      
      result.push(clone);
   }
  });

  return result;
}

console.log(getUnique(arr, 'id_0'));

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

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

Angular: the page continues to display outdated information after using router.navigate

My web app allows users to select products to purchase. They can pause the configuration process and resume it later. Currently, I am using localStorage to store information about the products and their prices. There is a page in my app that displays a ta ...

How can I effectively validate Django form errors using JavaScript prior to submission?

Is there a way to ensure that error messages in JavaScript client-side validation match those in Django server-side form validation? I've looked for a Django library that accomplishes this, but haven't had any luck. The closest question I found ...

Can you show me how to assign a string to a variable using a shorthand if statement?

In the following scenario, I intend for the NAME value to be set as "jack" if the condition is true: int main(){ char NAME[6]; NAME = (4 < 5 ) ? "jack" : "Linda"; } However, upon compiling this code, an error is encountered: ...

Error encountered while attempting to load image through multiple window.print() functions

I am having an issue with printing a receipt containing an image in a for loop when using the code below. The image does not load when multiple prints are done using the for loop (It works fine for a single print), but if I remove the image reference, it ...

What could be causing this JS file to not impact the DOM as expected?

Currently, I am delving into the world of JavaScript and trying to gain a better understanding of how to manipulate the DOM on my own. Throughout this learning process, I have encountered a puzzling situation that I am seeking assistance with. The followi ...

Get a document from a NodeJS Server with the help of Express

How can I improve my file downloading functionality in Node.js? Currently, when I try to download a PDF file from the server, the content is displayed as data instead of initiating the download process. I would like it to function similar to how it's ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

Hiddenfield value could not be located within the JavaScript function

After days of researching my issue, I am still struggling to get it working correctly. Although I have found some helpful information related to my problem, I seem to have hit a roadblock and could really use some guidance. I developed a small .NET 3.5 VB ...

Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it : <div class="map"> <div class="map-page" tabindex="0" @keyup.arrow-keys="show" ref="mapPage"> <template v-for="mapRow in mapMatrix"> < ...

Ways to divide a byte array

Here is a straightforward code snippet to split a byte array and observe its functionality. However, the issue I am facing is that I am getting unexpected outputs. public static void SplitArrayUsingLinq() { int i = 3; string data ...

Exploring the capabilities of CasperJS through double clicking

I'm currently working on creating a bot using CasperJS. The main goal is for the bot to send trade offers by offering an item, but I'm facing difficulties in figuring out how to click on the item. I attempted to use Resurrectio, however, it' ...

Creating dynamic lists and adding them to a map programmatically

In my code, I am working with an array that looks something like this: 006247241 0590040100000124 0590020100000125 0590020450000124 006247242 0590040100000129 ... If the length of any value in the array falls between 1 to 9, it becomes a key and the subseq ...

Attack on Titan: Issue: Uncaught (in promise): TypeError: Unable to access property '$' of unspecified

I recently attempted to deploy my Angular4 front-end project in AOT production build mode. It took a lot of time and effort to get the angular cli to successfully build in AOT mode, but I finally managed to publish the front-end that was previously deploye ...

Can Date.parse be utilized within an Angular expression?

I am struggling with the code below: function Ctrl($scope) { $scope.dt = new Date('2012-07-16T00:00:00'); var format = { day: '2-digit', month: '2-digit', year: 'numeric' }; $s ...

Rendering props conditionally in React

I am currently facing an issue with two different states retrieved from API calls: 'movieList' and 'search'. Both of them contain arrays of movies. The 'movieList' state is automatically rendered on the page to display popular ...

Determining the boundaries of the near and far planes for the camera calculations

In my attempt to calculate the near and far plane vertices using THREE.Frustum, I referenced a question on Stack Overflow (Calculate near/far plane vertices) and its corresponding answer (answer link). By combining the information provided, I created a w ...

What is the best way for me to individually extend the 3 collapsible cards on the page

How can I modify the code in Mui5 to only expand one card at a time when clicking on the specific button of the card? To see my example code and demo, visit: https://codesandbox.io/s/optimistic-cerf-pelzk7?file=/demo.js Here is a snippet of the sample co ...

What's the reason for the JSON not being returned?

I'm currently working on retrieving the latitude and longitude information from the Google Maps API. I've also been developing a PHP RESTful API to assist with this task. However, I seem to be encountering issues when trying to retrieve and displ ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...