Discovering identical objects by property and combining them with the help of JavaScript or UnderscoreJS

Below is an array that I have:

var somevalue = [{
    code: 1,
    name: 'a1'
  }, {
    code: 2,
    name: 'b1'
  }, {
    code: 1,
    name: 'a2'
  },
  {
    code: 1,
    name: 'a3'
  },
  {
    code: 2,
    name: 'b2'
  }
]

I am looking to identify duplicate elements based on the code, and then merge all elements with the same code into one. The desired output would be as follows:

var somevalue = [{
    code: 1,
    name: 'a1, a2'
  }, {
    code: 2,
    name: 'b1, b2, b3'
  }
]

Is it possible to achieve this using underscoreJS?

I currently can do this using a for-loop. However, in real-life scenarios, the array is quite large and contains JSON objects with multiple properties. Therefore, I am in search of a performance-oriented solution.

Answer №1

To condense an array, you can utilize the array.reduce() method:

var items = [{
    id: 1,
    type: 'apple'
  }, {
    id: 2,
    type: 'banana'
  }, {
    id: 1,
    type: 'orange'
  },
  {
    id: 1,
    type: 'pear'
  },
  {
    id: 2,
    type: 'grape'
  }
];

items = items.reduce((accumulator, current) => {
  const foundItem = accumulator.find(element => element.id === current.id);
  foundItem ? foundItem.type += `, ${current.type}` : accumulator.push(current);
  return accumulator;
}, []);

console.log(items);

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

Is there a way to incorporate personalized image placeholders into Next.js?

The Image component has properties called placeholder and blurDataURL. The placeholder property can have a value of either 'blur' or 'empty', with no other option. I tried setting the placeholder to 'blur' and specifying the b ...

Can you explain the distinction between using single and double quotes in my JavaScript and CSS code?

Is there a significant distinction between using single or double quotes in JS and CSS? Does it depend on personal preference, or are there certain instances where one is preferred over the other? In W3Schools, they employ single quotes for url('&apo ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

JQuery automatically selects an action upon 'change' event, but does not do so upon 'select' event

I'm hoping my explanation was clear. I have a text input field that utilizes the jQuery UI autoselect function. When a user selects an option, the input field auto-fills correctly. However, I encounter an issue when a user types something but does not ...

Is it better to append content in JQuery rather than replacing it with .innerHTML?

Here is a function designed to retrieve older wallposts from a user, 16 at a time, and add each chunk of 16 to the end of the current list in the div called "sw1". The function works well, except when there is a wallpost containing a video or embedded obj ...

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

methods for extracting json data from the dom with the help of vue js

Can anyone help me with accessing JSON data in the DOM using Vue.js? Here is my script tag: <script> import axios from "axios"; export default { components: {}, data() { return { responseObject: "" }; }, asy ...

The jQuery .accordion() feature is not functioning properly due to the failure to load jQuery into the HTML document

I have exhaustively researched online and visited numerous resources, including Stack Overflow. Despite making countless adjustments to my code, it still refuses to function properly. The frustration is mounting as I struggle with jQuery - a technology tha ...

Need help resolving the issue of "Type Property '' does not exist on type 'IntrinsicAttributes & Function'? Let's find a solution together

Looking at my parent component below: import FilterComponent from 'filter/filterComponent' const handleReload = useCallback( (event: MouseEvent) => { event.preventDefault(); // implement logic here }, [Reload, Fetch ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

Instructions on utilizing module.exports to export an async function

I am facing an issue with returning the result of an async function to the route I am calling. How can I resolve this successfully? My goal is to export a token from file token_generator.js and display it on route ('/') using Express. The functi ...

An undefined variable was encountered within the 'else' statement

I am encountering an issue with my code where it is returning an 'undefined' error. The problem arises when I attempt to remove an id from an array using the variable 'id', but instead, it throws an error stating 'undefined'. ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

What is the process of permanently modifying an HTML document using JavaScript?

I'm interested in creating a basic comment section using JavaScript. Here is the structure of the form : <form> <textarea cols="50" rows="10" placeholder="Share your thoughts ..." id="theComment"></textarea><br/> < ...

Clicking on ng-click can lead to the dissociation of the Angular factory

My situation involves a factory with a series of prototypes that need to call each other. The issue arises when the reference to "this" is mistakenly applied to the html template instead of the original factory class when using ng-click. For example: ang ...

Is it possible to execute the .push() method on an array a specific number of times without using a for loop?

Currently, I am tackling the "Move Zeroes" Leetcode challenge. The task requires moving all zeroes to the end of the array without altering the sequence of non-zero elements. My strategy involves iterating through the array, splicing out each zero encounte ...

Utilize JavaScript to extract an image from an external URL by specifying its attributes (id, class)

Is it possible to fetch an image from an external website by using its CSS id or class in conjunction with JavaScript/jQuery's get methods? If so, could someone provide guidance on how to achieve this task? ...

Experiencing issues with utilizing long polling on a node.js server URL in Internet Explorer

Currently, I am in the process of testing an application that utilizes long polling with jQuery to query a server built with node.js. The code for long polling is as follows: (function poll(){ $.ajax({ url: "http://localhost:3000/test", ...