Ways to combine the values of duplicate object arrays into one

I have a list of items with duplicate IDs and I want to merge them into one array for each unique ID. I have successfully found the unique IDs, but now I need help combining the names associated with those IDs.

const x = [
   {id: 1, name: 'green'},
   {id: 2, name: 'red'},
   {id: 1, name: 'blue'}
]

Desired output:

[
   {id: 1, name: 'green, blue'},
   {id: 2, name: 'red'}
]

Answer №1

Simply use the reduce method along with Object.values to achieve the desired result.

const data = [{
    id: 1,
    color: 'green'
  },
  {
    id: 2,
    color: 'red'
  },
  {
    id: 1,
    color: 'blue'
  }
]

const mergedData = Object.values(data.reduce((acc, item) => {
  if (acc[item.id]) {
    acc[item.id].color += ", " + item.color;
  } else {
    acc[item.id] = { ...item };
  }
  return acc;
}, {}));

console.log(mergedData);

Answer №2

  1. Loop through the elements in array x using the .reduce method and employ a Map to store each element's id as a key and its name as the value.
  2. If the map already contains an entry with the same id, append the current element's name to it.
  3. If not, create a new record for that id.
  4. By the end, the values of the map will hold all the array elements grouped by their respective id, with the names now encompassing all associated values.

const x = [ { id: 1, name: 'green' }, { id: 2, name: 'red' }, { id: 1, name: 'blue' }
];

const res = [...x.reduce((map, {id, name}) => {
  if(map.has(id)) map.get(id).name += `, ${name}`;
  else map.set(id, { id, name });
  return map;
}, new Map)
.values()
];

console.log(res);

Answer №3

Effective method utilizing the Set data structure to extract a roster of distinct identifiers.

Subsequently, employing filter and map operations to retrieve all relevant objects, followed by combining their names using join.

const x = [
   {id: 1, name: 'green'},
   {id: 2, name: 'red'},
   {id: 1, name: 'blue'}
]

const result = [];
const uniqueIds = [...new Set(x.map(item => item.id))];
const merged = uniqueIds.forEach((id) => {
  
  // Identify matching ids
  const match = x.filter((o) => o.id === id);
  
  // Assemble names of matching ids
  const names =  match.map(x => x.name);
  
  // Append new data
  result.push({
    id,
    names: names.join(', ')
  });
});

console.log(result);

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 manipulate CSS to update automatically when new content is loaded via ajax?

I need help with customizing the CSS for 4 image links on my website. Each link is represented by a small image in its normal state and a larger image when hovered over. The content for each link is loaded using ajax. My question is how can I modify the C ...

Guide on triggering a modal upon receiving a function response in React

I am looking for a way to trigger a function call within a response so that I can open a modal. Currently, I am utilizing Material UI for the modal functionality. Learn more about Modals here The process involves: Clicking on a button Sending a request ...

How can I change the "Return" button on the iOS keyboard to a "Next" button using jQuery or JavaScript?

Currently, I am developing an HTML application and working on implementing it for IOS devices such as the IPAD. Within my application, there are multiple text boxes. Whenever a user clicks on a text box to input text, the keypad appears. On this keypad, ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

Rapidly typing text into a text box using Selenium and Python

Currently, I am utilizing Selenium in conjunction with Python (Chrome driver) to populate text boxes. However, the process is taking longer than desired due to the presence of numerous textboxes. My solution involves using a series of driver.find_elemen ...

Tips for resolving Vue.js static asset URLs in a production environment

I included the line background-image: url(/img/bg.svg); in my CSS file. During development mode, this resolves to src/img/bg.svg since the stylesheet is located at src/css/components/styles.css. However, when I switch to production mode, I encounter a 40 ...

Improving the Speed of ASP.NET TreeView

How can we optimize performance when using the TreeView component? When I say optimize performance, I am referring to reducing the number of client-server trips, such as postbacks. Does this imply that the majority of the business logic will need to be i ...

Encountering the error message "handleChange is not a function" when trying to select a date in Material UI

Encountering an error message 'handleChange is not a function' when selecting a specific date in the DatePicker component. The DatePicker component is nested within the Controller component of react-hook-form. The expected behavior is to display ...

Endless asynchronous loops with setInterval()

My nodejs application requires multiple infinite loops that call asynchronous functions. I was contemplating the following approach: async function process1() { ...perform some asynchronous tasks... } async function process2() { ...perform some as ...

What is the best way to ensure that text moves to the next line if it exceeds the boundaries of the parent div in either CSS or

I am looking to have the "remaining books count" and "remaining pens count text" automatically move to the next line below the numbers when they exceed two digits, causing an overflow in their parent div. Here is the code snippet I currently have: functi ...

ReactJS - Error: Attempting to access the property 'raw' of an undefined variable

I'm currently facing an issue where I am trying to extract specific data from a particular part of an api. Surprisingly, I can view all the data in the console. { "id":"DszAeHV8zfQ", "created_at":"2020-01-28T19:41:06-05:00", "updated_at":"2020 ...

To make the Bootstrap 4 spinner/loader gracefully disappear when the browser window has finished loading, utilize the fadeOut() or hide() function

THE GOAL My objective is to display a spinner/loader while the browser window is loading, and then have it fade or hide once the page is fully loaded. EFFORTS MADE I've attempted to use a jQuery code recommended in a different question (How to show ...

Ways to navigate back to the previous page on Vue router while replacing the current state

Looking for a way to go back using the replace method in Vue router? router.replace() I couldn't find any documentation on how to achieve this. My goal is to remove the current state from the history stack and navigate back to the previous page with ...

The Angular bootstrap popover vanishes as soon as the mouse hovers over it

Currently, I am facing an issue with an angular bootstrap popover on some text. The problem arises when the user tries to click on a link inside the popover as it disappears. Additionally, when changing from one popover to another, the previous one does no ...

Having trouble utilizing the $ selector within a for loop? Avoid attempting to use $("$i") and try an alternative method instead

for (var i = 0; i < 9; i++) { a[i] = val($("#" + i)); alert(a[i]); } UPDATE: The previous code was incorrect as it selected elements with id(#) 'i', which is invalid. Therefore, "#" + i should be used instead. My query was: How c ...

Ensure all division elements have the same height by utilizing a directive

My webpage currently displays a grid that is not properly arranged. However, when I executed the code below in the console, the grid was formatted correctly: var maxHeight = Math.max.apply(null, $("#activityfeeddetails").find(".course_thumb_outer").map(fu ...

Performing various JavaScript functions within a single hyperlink

I've implemented the Tab Content Script by dynamicdrive.com on my website. The script creates tabbed navigation, and I find it to be quite useful. Currently, I am trying to figure out how to make a single link select two tabs at once. Essentially, I ...

The Ajax response is revealing JavaScript instead of concealing it

Currently, I am developing a comment system with various features such as deleting the main post, deleting comments, deleting replies, editing the main post, editing comments, editing replies, and implementing Read More/Read Less for posts longer than 250 ...

How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps. I have obtained this SVG file: <svg xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510"> <g stroke="black" stroke-width="10" ...

The entire DOM has been seamlessly replaced by React.JS within the Node.js server

I am currently focusing on practicing the MERN structure, so my goal was to start by setting up a node.js server and react front-end. However, I encountered an issue where the entire DOM gets overwritten once the server is fired up. This has left me wonde ...