Home > Mobile >  Remove duplicate values and overwrite the array
Remove duplicate values and overwrite the array

Time:12-09

There is such an array:

[
    { message: '12949', author: 'esP' },
    { message: '1609', author: 'user' },
    { message: '1613', author: 'adm' },
    { message: '12949', author: 'Mdr' },
    { message: '12949', author: 'rood' }
]

How can you make sure that messages are not repeated, the authors are written separated by commas:

[
    { message: '12949', author: 'esP, Mdr, rood' },
    { message: '1609', author: 'user' },
    { message: '1613', author: 'adm' }
]

I check for uniqueness this way:

const _ = require('underscore');
let a = _.uniq(arr, x => x.message)

What to do next? Create a second loop and compare values?

CodePudding user response:

We can use Array.reduce(), to get the required result.

We'd add each item to a map object (accumulator), using the message value as the key, then use Object.values() to return our desired result array:

const arr = [ { message: '12949', author: 'esP' }, { message: '1609', author: 'user' }, { message: '1613', author: 'adm' }, { message: '12949', author: 'Mdr' }, { message: '12949', author: 'rood' } ];

const result = Object.values(arr.reduce((acc, { message, author }) => { 
    if (!acc[message]) {
        acc[message] = { message, author };
    } else {
        acc[message].author  = `, ${author}`;
    }
    return acc;
}, {}));

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

CodePudding user response:

const data = [
    { message: '12949', author: 'esP' },
    { message: '1609', author: 'user' },
    { message: '1613', author: 'adm' },
    { message: '12949', author: 'Mdr' },
    { message: '12949', author: 'rood' }
]
const result = [];
for (const item of data) {
  const index = result.findIndex(d => d.message === item.message);
  if (index === -1) {
    result.push(item);
  } else {
    result[index].author  = `, ${item.author}`;
  }
}
console.log(result);

CodePudding user response:

A simple method of having a temporary array and updating it if message is already found. Or concatenting the author otherwise:

var original = [
    { message: '12949', author: 'esP' },
    { message: '1609', author: 'user' },
    { message: '1613', author: 'adm' },
    { message: '12949', author: 'Mdr' },
    { message: '12949', author: 'rood' }
]
var result = [];

for (let data of original) {
  let existingResult = result.find(obj => obj.message == data.message);
  if (existingResult)
    existingResult.author  = ", "   data.author;
  else
    result.push(data)
}
console.log(result);

  • Related