Home > Software engineering >  Angular/Javascript Merge array elements with condition
Angular/Javascript Merge array elements with condition

Time:09-20

I want to merge 2 array elements to avoid duplicate values

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

Output should be

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

If ids are the same then name strings should be concatenated with OR. How can i do this using Angular or javascript function? Can i do this using array.reduce() function? if yes how can i do that? Or do i need to use for loop only?

CodePudding user response:

You can use Array.reduce() to group the items by id.

This creates an object with a property for each id, we can then use Object.values() to get the result 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]) {
        // Create a new entry in our map...
        acc[id] = { id, name };
    } else { 
        // Append to the existing entry in our map...
        acc[id].name  = ' OR '   name;
    }
    return acc;
}, {}))

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

You can also use a for...of loop to get the same result:

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; }

CodePudding user response:

This is fairly easily done. What have you tried before? There are multiple ways to achieve this.

Here is some quick pseudo code I threw together to help you:

result = []
idsFound = []

//Go over all elements in input array
for x = 0, x < array.length, x  
    element = array[x]
    
    //Id was already handled
    if idsFound.indexOf(element.id) !== -1:
        continue
    
    //Go over all upcoming elements
    for y = x   1, y < array.length, y  
        other_element = array[y]
        
        //Check if id matches
        if other_element.id === element.id:
            //Append name
            element.name  = ' OR '   other_element.name
    
    //Push element and id
    result.push(element)
    idsFound.push(element.id)
            

  • Related