Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates?

array = [
  {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}
];

The desired output is:

result = [{id: 1, name:'abc OR xyz'},{id: 2, name:'text1 OR text2'}];

If the ids are the same, the name strings should be concatenated with 'OR'. How can this be achieved using Angular or JavaScript functions? Can it be done using the array.reduce() function? If so, how would that look like? Or do I have to resort to using a for loop?

Answer №1

To group the items by their id, you can utilize the Array.reduce() method in JavaScript.

This approach will create an object with a property for each unique id, and then you can extract the grouped result using Object.values() to obtain it as an array.

const array = [{id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}];

const result = Object.values(array.reduce((acc, { id, name }) => { 
    if (!acc[id]) {
        acc[id] = { id, name };
    } else { 
        acc[id].name += ' OR ' + name;
    }
    return acc;
}, {}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

An alternative way is to achieve the same outcome using a for...of loop:

const array = [{id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}];

const map = {};

for(let { id, name } of array) {
    if (!map[id]) { 
        map[id] = { id, name };
    } else { 
        map[id].name += ' OR ' + name;
    }
}

const result = Object.values(map);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

Answer №2

Completing this task is quite simple. What methods have you attempted previously? There are numerous approaches to accomplishing this goal.

Below is a brief snippet of pseudo code I put together to guide you:

result = []
idsFound = []

//Iterate through all elements in the input array
for x = 0, x < array.length, x++
    element = array[x]
    
    //Check if ID has already been processed
    if idsFound.indexOf(element.id) !== -1:
        continue
    
    //Iterate through upcoming elements
    for y = x + 1, y < array.length, y++
        other_element = array[y]
        
        //Verify if IDs match
        if other_element.id === element.id:
            //Add name information
            element.name += ' OR ' + other_element.name
    
    //Add element and ID to result arrays
    result.push(element)
    idsFound.push(element.id)
            

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

Prevent form submission with jQuery during validation process

Currently, I am working on validating a form using jQuery. My main objective now is to have the submit button disabled until all fields are correctly filled in. To achieve this, I have implemented the following approach: http://jsfiddle.net/w57hq430/ < ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

What are the steps to utilizing an npm package that simply encapsulates my JavaScript code?

Our current npm package is designed for clients working on ES6-based projects, such as React. The main index file of the package looks like this: export function ourFunction() { } Clients import this function using the following syntax: import { ourFunc ...

Separate PHP variables from a MySQL array by splitting them

I'm quite new to PHP, so bear with me if I'm posing the wrong question or inquiring about something overly basic. Within my MySQL table resides static data detailing base stats for players. My task is to exhibit each player's stats individu ...

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

Incorporating responsive design with React and Typescript

Trying to utilize React with TypeScript, I aim to dynamically generate components based on a field name // Storing all available components const components = { ComponentA, ComponentB, }; // Dynamically render the component based on fieldName const di ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

Exploring Composite Types with TypeScript's `infer` Keyword

After implementing redux in my project, I found myself including the following code snippet in my store: type CombinedParamTypes<T extends { [key: string]: (state: any, action: any) => any; }> = T extends { [key: string]: (state: infer R, ...

Customizing error styles in a table using Jquery validation

My form is using JQuery .validation(). Here is the structure of my form: <form....> <table cellspacing="0" cellpadding="0"> <tr> <td>Name: </td> <td><input type='text' name='Name'/></td> ...

Why should one bother with specifying types when defining a variable in Typescript?

As someone new to Typescript, I've come to appreciate its many advantages when working on larger applications and with multiple team members :) Imagine you have the following TypeScript code: declare const num = 5: number; Why is this better than: ...

Can README docs be prioritized to appear before all other stories in Storybook navigation?

Organizing my Storybook stories is important to me. I like to nest all my stories under a “Docs” header, with each component having a README mdx file followed by its stories. My preferred order is to always have the README appear first in the navigatio ...

Having trouble with JSON search not functioning as expected in Select2 4.0?

After numerous hours of effort, I finally managed to successfully load and display the json file, complete with the flag icons using Select2 4.0. The code ended up appearing deceptively simple. However, I am now facing an issue where the search function i ...

Issue with Firefox-Android causing dropdown toggle to malfunction

When I manually trigger a dropdown, it closes when any click is performed outside of it (while open). This code works in all browsers except for Firefox on Android. Why does this happen? It seems like the event parameter doesn't reach the function ...

When I apply filtering and grouping to the table, the rows in the mat table disappear

When using mat-table, grouping works fine without filtering. However, once the table is filtered or if the search bar is focused, ungrouping causes the rows in the table to disappear. I am looking for a solution that allows me to group and ungroup the tabl ...

Creating a dropdown menu using Vue.js

My latest project involves coding an html page that features a drop-down list using HTML, CSS, and VueJS. The goal is to have something displayed in the console when a specific option from the drop-down list is selected. Here's the snippet of my html ...

The error message "Unexpected TypeError: useSearchParams either does not exist as a function or is not iterable in its return value

I'm currently facing a problem with my code, which results in the error message: "Uncaught Error: NextRouter was not mounted" appearing in the console. After some investigation, I discovered that with Next.js version 13 onwards, we should ...

The AngularJS directive "ng-include" is used to dynamically

I am encountering an issue with ng-include not retrieving the file. What could be the reason for the problem in accessing a property from a link within ng-include? I would appreciate any assistance with resolving this matter. (function(){ var app = angu ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...

The dropdown height feature is experiencing issues in the Chrome browser

3 radio buttons and a single select box are displayed on the page. When clicking on the first radio button, the select box should show contents related to the first radio button. However, when selecting the second or third radio buttons, the select box hei ...