Bring together a set of elements within a collection of identical entities that contain corresponding key-value pairs by utilizing JavaScript

Looking at the object below:

  a = [
{id: 1, comp: 'ans', stat: 'www', value: ['1', '2']},
{id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']},
{id: 3, comp: 'ans', stat: 'yyy', value: ['3', '4']},
{id: 4, comp: 'qsn', stat: 'zzz' ,value: ['c', 'd']}
]

I am seeking an optimal method to combine the value arrays within objects where the key comp matches and retain the other properties as they are for the first element, while concatenating only the values array. The desired output in this case is :

[
{id: 1, comp: 'ans', stat: 'www', value: ['1', '2', '3', '4']},
{id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b', 'c', 'd']}
]

Answer №1

To group the items based on their comp property, you can use the Array.prototype.reduce function along with Object.values to extract the grouped objects.

const a = [{id: 1, comp: 'ans', stat: 'www', value: ['1', '2']},{id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']},{id: 3, comp: 'ans', stat: 'yyy', value: ['3', '4']},{id: 4, comp: 'qsn', stat: 'zzz' ,value: ['c', 'd']}],
      result = Object.values(a.reduce((a, {comp, value, ...rest}) => {
        (a[comp] || (a[comp] = {...rest, comp, value: []})).value.push(...value);
        return a;
      }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

We need to consider a more easily understandable method

const data = [{
        id: 1,
        type: 'cat',
        status: 'active',
        values: ['meow', 'purr']
    },
    {
        id: 2,
        type: 'dog',
        status: 'inactive',
        values: ['woof', 'bark']
    },
    {
        id: 3,
        type: 'bird',
        status: 'active',
        values: ['tweet', 'chirp']
    },
    {
        id: 4,
        type: 'fish',
        status: 'inactive',
        values: ['bubble', 'swim']
    }
]

const finalResult = [];

for (let item of data) {
    const sameType = finalResult.find(res => res.type === item.type);
    if (sameType) {
        sameType.values = sameType.values.concat(item.values);
    } else {
        finalResult.push(item);
    }
}

console.log(finalResult);

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

The JsonConverter in C# is able to transform properties based on the specific class

I am looking to create a JsonConverter that can convert a specific property type based on the class in which it is defined. I have set up the JsonConverter globally via Web API: var config = GlobalConfiguration.Configuration; var jsonSettings = config.Fo ...

Is there a way to retrieve the date of the most recent occurrence of a specific "day" in TypeScript?

Looking to retrieve the date (in YYYY-MM-DD format) for the most recent "Wednesday", "Saturday", or any user-specified day. This date could be from either this week or last week, with the most recent occurrence of that particular day. For instance, if toda ...

Extracting information from a JSON in MySQL - A step-by-step guide

I have some data to work with: set @j = '[{"id": 1, "title": "John"}, {"id": 2, "title": "Mary"}, {"id": 3, "title": "Alex"}]'; Select REPLACE(REPLACE(REPLACE(JSON_EXTRACT(@j, '$**.*'),"[",""),"]",""),&apos ...

How can you merge one object with two different mongoose models?

Consider the scenario where I have two mongoose models set up: User Model Business Favorite Model Currently, I'm successfully retrieving the combined result if a user has any favorite businesses. However, I suspect that my current implementation mi ...

generate a collection using a string of variables

I'm looking for a way to pass a string as the name of an array to a function, and have that function create the array. For example: createArray('array_name', data); function createArray(array_name, data){ var new_array = []; // pe ...

Enhance user experience by implementing an interactive feature that displays

I have a form for adding recipes, where there is an ingredients button. Each recipe can have multiple ingredients. When the button is clicked, an input field for adding ingredients should appear below the ingredient button. What I've attempted so far ...

Create a TypeScript type that represents an empty collection

I recently acquired some knowledge about TypeScript through a university course I took this month. Is it possible for this to represent an empty set? type emptySet=0&1; Whenever I attempt to assign this to any value (for example: boolean, number, st ...

What is the best way to ensure my dropdown menu closes whenever a user clicks anywhere on the page? (javascript)

I have created a dropdown that appears when the user clicks on the input field, but I would like to remove the active class so that the dropdown disappears if the user clicks anywhere else on the page. Here is my code snippet: // drop-down menu functi ...

Interactive html5 canvas game with swiping mechanism

Currently, I am in the research phase for a new HTML5 canvas game that I want to create as a personal project to enhance my skills. Surprisingly, I have not been able to find any valuable articles or tutorials online about creating swipe-based games. The ...

Anticipating the completion of loading the JSON API without the use of Docker

I need help retrieving JSON data from a government website using R and the jsonlite package. The issue I'm facing is that it seems to only grab 1000 rows of data, even though there should be around 32,000. My suspicion is that the webpage isn't f ...

Is there a way to refactor the onAuthStateChanged function from useEffect in firebase to a class component?

Below is the code snippet used in the function component: useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { setIsLoggedIn(!!user); }); return () => { unsubscribe(); }; }); And here is ...

Experiencing issues with regex in JavaScript: all text enclosed within <angular> brackets vanishes

I am trying to analyze a formula and present it on the screen. For instance, I want to be able to input <path>T Q, where <path>T remains unchanged, and Q is a variable. It accepts this input, but when displaying it on the screen, only T Q shows ...

Separate a string containing commas and quotes into individual elements in a Bash array

I am trying to split a comma separated, but quoted list of strings into an indexed bash array within a script. While there are many resources online and on stack overflow that demonstrate how to create an indexed array from a given line or string, I have ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

What is the most effective method for distributing TypeScript functions that are used by services and span multiple components?

I have a set of TypeScript functions that are currently scattered across components. These functions are being duplicated unnecessarily, and I am looking for a way to centralize them so all components can access them without redundancies. Since these fun ...

JSON.stringify omits any properties in a custom class that have not been explicitly declared in the constructor

I recently defined a new class in my code: export class SavedData{ public isDone : boolean; } After trying to stringify an instance of this class, I noticed that the isDone property was not included: console.log(new SavedData()); This resulted in a ...

The JavaScript syntax dollar sign

I am currently studying a JavaScript source code and it's my first time writing JavaScript. I find some of the syntax confusing. <script id="source" language="javascript" type="text/javascript"> $(function () { window.onload=function() ...

Repetitive invocation of functions

I am presenting a listing HTML structure as follows <li class="game-box showlist" id="papp_1249" data-tag="Junior KG,Maths"> <div class="game-box-link" data-id="1249" data-active="yes" data-orientation="landscape" data-ajax="fal ...

The hover feature in jQuery may encounter issues when implemented with Angular's ng-repeat directive on objects

I have successfully implemented a jQuery hover function: $('.deleteButton').hover(function(){ $(this).css('opacity', '1'); }, function(){ $(this).css('opacity', '.5'); }); The function was functi ...

What is the best way to resolve the unusual resolution issue that arises when switching from Next.js 12 to 13

Previously, I created a website using nextjs 12 and now I am looking to rebuild it entirely with nextjs 13. During the upgrade process, I encountered some strange issues. For example, the index page functions properly on my local build but not on Vercel. ...