Combining an array into another array using the same key in JavaScript

My goal is to merge the array itself and transform it into a more meaningful array

array = [
{item: 'pen', madeIn: 'US', color: 'blue'},
{item: 'pen', madeIn: 'US', color: 'white'},
{item: 'pen', madeIn: 'China', color: 'red'},
{item: 'pen', madeIn: 'China', color: 'white'}
]

The desired output array I am trying to create :

outputArray = [
{item: 'pen', madeIn: 'US', color: ['blue', 'white']},
{item: 'pen', madeIn: 'China', color: ['red', 'white']}
];

I have attempted different methods without success. One solution involves using a temporary variable to store item and madeIn values, followed by another loop to compare items and madeIn values and then add colors to an array. Multiple loops are needed to solve this issue.

While this method works, it is not the most efficient solution. Any other ideas or suggestions would be greatly appreciated. Thank you.

Answer №1

Utilize the reduce method on the array to transform it into an object by creating a key based on the item and madeIn properties. For each object, check if the key already exists; if not, create a new object for the key with an empty array as the color property. Add the color of each object to this array. Finally, convert the object to an array using Object.values().

const array = [{"item":"pen","madeIn":"US","color":"blue"},{"item":"pen","madeIn":"US","color":"white"},{"item":"pen","madeIn":"China","color":"red"},{"item":"pen","madeIn":"China","color":"white"}]

const result = Object.values(
  array.reduce((r, o) => {
    const key = `${o.item}-${o.madeIn}`
    
    if(!r[key]) r[key] = { ...o, color: [] }
    
    r[key].color.push(o.color)
    
    return r;
  }, {})
)

console.log(result)

Answer №2

Utilize the reduce function:

const items = [{ name: 'shirt', brand: 'Nike', color: 'black' }, { name: 'shirt', brand: 'Adidas', color: 'white' }, { name: 'shoes', brand: 'Reebok', color: 'red' }, { name: 'pants', brand: 'Puma', color: 'blue' }];

const result = Object.values(items.reduce((acc, { name, brand, color}) => {
  acc[`${name}-${brand}`] = acc[`${name}-${brand}`] || { name, brand, color: [] };
  acc[`${name}-${brand}`].color.push(color);
  return acc;
}));

console.log(result);

Answer №3

Check out this innovative solution that leverages Array.prototype.reduce() along with object destructuring:

const initialItems = [
  {name: 'book', origin: 'US', category: 'fiction'},
  {name: 'book', origin: 'US', category: 'non-fiction'},
  {name: 'book', origin: 'UK', category: 'mystery'},
  {name: 'book', origin: 'UK', category: 'romance'}
];

const finalItems = initialItems.reduce((accumulator, currentValue) => {
  const item = accumulator.find(x => x.name === currentValue.name && x.origin === currentValue.origin);
  if(item) {
    item.category.push(currentValue.category);
  }
  else {
    accumulator.push({...currentValue, category: [currentValue.category]});
  }
  return accumulator; 
}, []);

console.log(finalItems);

This approach stands out for its independence from a conventional key structure and ability to handle diverse datasets.

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

Display the preloaded element as the first item using Javascript

Is there a way to prioritize the loaded elements using JavaScript? I have an array of elements that I pass to a function and make an AJAX call. While the data is loading, I display a loader (.gif). I want to ensure that the loaded elements are shown first ...

Utilize your access token to send a message through Google Business Messages

Currently, I have successfully set up a method to send messages using the Google Business Messages API from an agent to a user through NodeJS. const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); This process requires authenticatio ...

Retrieving an AJAX array POST in Laravel 5 Controller

Below is the structure of my form: <td> <input type="text" name='name[]' class="form-control"/> </td> <td> <input type="text" name='mail[]' class="form-control"/> </td> <td> <select na ...

Leveraging the power of the 'var' keyword in JavaScript when

I have a javascript code snippet that looks like this: var grade_type = document.getElementById("grade_type").value; gradesRef.set({ grade_type: firebase.firestore.FieldValue.arrayUnion(grade) }); However, when the data is stored i ...

What is preventing me from utilizing a dynamic import while working with Nuxt3?

I'm currently working on developing a component that allows me to dynamically import icons based on the provided icon name using unplugin-icons. However, I'm facing an issue where dynamic imports don't seem to work when the import path is dy ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

What is the best way to show TypeScript code using "<code>" tags within an Angular application?

I am looking to showcase some TypeScript (angular code) as plain text on my website using prismjs. However, the Angular framework is executing the code instead. How can I prevent it from running? I have attempted enclosing it within pre and code tags wit ...

Is it possible to make a distinctive choice from the dropdown menu?

I need help with my html page that has 10 dropdowns, each with options 1 to 10. How can I assign options uniquely to each dropdown? For example, if I select option 1 in dropdown 1, that option should be removed from the other dropdowns. If I deselect an ...

Bower downloads the identical package but arranges it in a distinct file structure

We operate a TeamCity build server that is utilizing three different buildusers all configured similarly. We have integrated an angular/grunt project using yeoman Update 6 Noted an issue with bower https://github.com/bower/bower/issues/1709 Why does bow ...

Invoke the C# function in the code-behind using an AJAX call

I have been attempting to encrypt two variables and return them as query strings using a code-behind function, but I have not been successful. This is my first time trying Ajax. Here is the method in my code-behind: [WebMethod] public static string Encri ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

Clearing selections from a multiple-choice input field

I am seeking to implement a delete feature in a multi-select element similar to the functionality seen here on stackoverflow when selecting multiple tags for a question. Once an item is selected, I would like to display a close icon next to it so that user ...

Anticipated an expression prior to 'char' syntax

Struggling with my CSC assignment where I need to create a character array from my name (e.g. John Doe). The task involves passing a pointer of the character array to a function that counts the number of characters stored. This function should then return ...

Discovering the presence of line breaks

I have searched extensively on Google, but I am struggling to find a definitive answer. My goal is to create an email simulation where users can input text into a textarea and save it to the database. They should then be able to return to the page later a ...

Is it possible to launch a browser window using javascript?

I need to open a new Internet Explorer browser window and I am currently using the following code: window.open("http://jsc.simfatic-solutions.com", "mywindow"); However, I would like to know how can I open a new IE window with a fresh session? ...

Exploring MongoDB: Uncovering the array elements within nested objects in a collection's property

My Mongo DB database is configured with a collection called Races: [ { "_id": "5a24b47f8b8498252a0a0ef9", "year": 2017, "runners": [ { "Place": "1", "Div/Tot": "1/126", ...

Invisibility of form data on new page - PHP and Javascript

I have a webpage with multiple hyperlinks. Each hyperlink should redirect the user to a new page with the URL sent as POST data. What I can do: 1. Open the new page successfully. The issue I'm facing: 1. On the new page, I cannot access the URL ...

jQuery struggles to locate the active class within the Bootstrap slider

Want to make some changes to the Bootstrap slider? Here is the HTML Code and jQuery: <div id="carousel-slider2" class="carousel slide bs-docs-carousel-example"> <ol class="carousel-indicators"> & ...

Leverage the power of jQuery to fetch data from a PHP script connected to a MySQL database

It might be a bit confusing, so let me clarify. I'm working on a form where users input a ticket and it gets assigned to a technician based on the service they offer. I have 3 text fields: username, email, and description of the problem. The next fie ...