Locate identical items within an array of objects by comparing their value properties, then merge these duplicates by appending the duplicate object to its label property through array reduction

Let's imagine I have an array of objects structured like the following:

[ 
    {value: "2021", label: "REDS"},
    {value: "2020", label: "REDS"},
    {value: "2021", label: "COPASA"},
    {value: "2021", label: "CEMIG_CLIENTES"},
    {value: "2016", label: "CEMIG_CLIENTES"},
    {value: "2016", label: "RFQSA"}
]

The task at hand is to identify duplicate entries based on the value property and create a new array that combines their label properties. The desired output should look like this:

[ 
    {value: "2021", label: "REDS/COPASA/CEMIG_CLIENTES"},
    {value: "2020", label: "REDS"},
    {value: "2016", label: "CEMIG_CLIENTES/RFQSA"}
]

How can I go about achieving this? I'm currently stuck in my attempts. I've tried extracting unique values using the following code snippet:

 const unique =  arr.map(e => e['value'])
             .map((e, i, final) => final.indexOf(e) === i && i)
             .filter(obj=> aux2[obj])
             .map(e => aux2[e]);

However, this approach falls short as it overlooks the preservation of labels. Another idea I had was to sort the array and devise a method to pinpoint duplicate positions so they can be merged accordingly. But so far, I haven't been successful in implementing it. Is there perhaps a more effective solution out there? If not, could someone offer guidance on how to tackle this challenge?

Thank you for your help in advance!

Answer №1

To achieve this, utilize a for loop to iterate through the objects, create a new array, and check if the value already exists. If it does, concatenate the label to the existing entry; otherwise, add a new one:

function removeDuplicateValues(arr) {
  const newArray = [];

  for (const object of arr) {
    const foundValue = newArray.find((element) => element.value === object.value);
    if (foundValue) {
      foundValue.label += "/" + object.label;
    } else {
      newArray.push(object);
    }
  }
  
  return newArray;
}

console.log(removeDuplicateValues([ 
  {value: "2021", label: "REDS"},
  {value: "2020", label: "REDS"},
  {value: "2021", label: "COPASA"},
  {value: "2021", label: "CEMIG_CLIENTES"},
  {value: "2016", label: "CEMIG_CLIENTES"},
  {value: "2016", label: "RFQSA"}
]));

If optimizing performance is crucial, consider using an object as the newArray with the value as the key. This way, you can avoid performing a .find operation in each iteration.

Answer №2

function mergeSimilarItems (arr) {
    const map = {};
    arr.forEach(item => {
        if (!map[item.name]) {
            map[item.name] = item;
        }
        else {
            map[item.name].quantity += item.quantity;
        }
    });

    return Object.values(map);
}

console.log(mergeSimilarItems([ 
    {name: "Apple", quantity: 3},
    {name: "Banana", quantity: 5},
    {name: "Apple", quantity: 2},
    {name: "Orange", quantity: 4}
]))

Answer №3

If you are in need of a solution, check out this universal method inspired by the response from Giorgi Moniava. I have condensed the code and added the option to choose your own key for identifying duplicates, along with a callback function to determine how values should be combined. In my scenario, I prefer to concatenate duplicate values using a pipe delimiter (refer to usage below).

function mergeDuplicates(array, duplicateKey, combineFunction) {
    return Object.values(
        array.reduce((accumulator, item) => {
            const id = item[duplicateKey];
            accumulator[id] = accumulator[id] ? combineFunction(accumulator[id], item) : item;

            return accumulator;
        }, {})
    );
}

example

mergeSimilar(myArray, "duplicateKey", (main, duplicate) => {
            
    return {
        ...main,
        value: [main.value, duplicate.value].join("|") 
    };
});

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

Does turning off javascript in a browser impact ajax requests and javascript functions?

My mind is troubled I've been thinking of options like turning off JavaScript in the browser. If I do that, then AJAX and JavaScript functions won't work, right? If so, is there a solution? ...

Ways to display console.log output in VS Code?

Sorry if this question is a bit unclear, but I'm struggling to figure out how to display the results from my console.log (line 14) in the console/terminal. I want to see the random RGB values generated for each column every time I click the button, bu ...

Performing a bitwise comparison in JavaScript

In the game I play, a specific number in the database is initially set as 100663296 to represent a GM Leader. However, this field in the database can be written to for various purposes, leading it to change the number to 100794368. I was advised to conside ...

Updating website elements using jQuery

Hello, I'm just starting out as a web developer and I have this script: function updateBaskket(productId, quantity) { $.ajax({ type: 'GET', url: '/update-basket', dataType: "json ...

Issue: encountered a write EPIPE error while attempting to transfer a file to FTP via gulp

Whenever I try to deploy some stylesheets to a server using FTP, I encounter an error about 80% of the time. Here's the specific error message: Error: write EPIPE at _errnoException (util.js:1022:11) at WriteWrap.afterWrite [as oncomplete] (net.j ...

Creating dynamic array indexes with user-defined keys during runtime

Here I am attempting to utilize the XMLSerializer class in order to convert data from a MySQL table into an XML file. My goal is for the XML file to have a specific structure. In order to achieve this, I need to transform the numeric indexes into 'bo ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Issues with embedding Soundcloud in Firefox

I've been grappling with a project that requires embedding Soundcloud songs. While everything functions perfectly in Chrome, Firefox presents a gray box with the Soundcloud logo instead. After attempting to troubleshoot using Firebug, I encountered t ...

Error: Controller not found when angular.module is called from different files

As I am restructuring my code to make it more modular, I decided to move the controller into a separate file that belongs to the same module. However, I am facing an issue where the controller does not load, even though I have verified that the load order ...

Create a unique component in ReactJS with the react-google-maps package to enhance your user interface

I would like to integrate a custom marker component into the map, but I have observed that using react-google-maps/api does not support rendering custom components. To illustrate this, here is an example of the code I used: const CustomMarker = ({ text }) ...

The system has encountered an issue: Unable to locate the module 'avoriaz'

I'm currently diving into Vue for the first time and have been following along with this helpful tutorial on testing. Everything was going smoothly until I encountered a perplexing error during the final step of utilizing avoriaz: ERROR in ./test/uni ...

CoffeeScript:: I can't understand why the function body returns when using ajax

Hey there, I'm new to Coffeescript and have a question regarding Ajax. jQuery -> api = getId: -> res = [] $.ajax dataType: "jsonp" url: "http://localhost:3004/videos.json" success: (data) => ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Toggle the visibility of an HTML element and dynamically change the text of a button

As a beginner in Javascript, I am experimenting with changing button text upon the show/hide of a fieldSet. However, I am encountering some issues with the button text not updating correctly. $(window).on("load", function() { $('.indoor').sl ...

Is there a way to modify a document without altering its original location?

I attempted to load an entire page using ajax, with the doctype and html tags removed. However, when I tried setting it with the following code: document.documentElement.innerHTML=xmlhttp.responseText; Google Chrome returned an error message: An invalid ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Showcasing pictures with a prominent large image accompanied by two smaller ones on the right side

In my use of Material-ui-next, I am attempting to create images in a specific layout. ------ --------- | | | | 2 | | | | 1 |---| | | | | 3 | ------ --------- I have encountered some unusual issues. 1 - 3 appears below 1 ...

PHP issue with accepting parameters in a function

Currently facing an issue with a PHP function. The function is declared as follows: function edit_content($array, $id = NULL){ //code } In this function, $array is the array passed as parameter and $id is an optional integer value. When I ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

Displaying an array in a fresh window with the help of jQuery

I'm working on a PHP page that includes a PHPlot image and I'm trying to figure out how to add a button that will display the data values either in a new window or an alert screen. However, the array size exceeds 10k values so displaying it in an ...