0

Good night. Some charitable soul to help me with a problem about javascript objects. Thank you very much who can ...

var arrA = [
    {language:'php', count_access:5},
    {language:'c', count_access:7}
];

var arrB = [
    {language:'php', count_access:0},
    {language:'c', count_access:0},
    {language:'python', count_access:0},
    {language:'ace', count_access:0},
    {language:'electron', count_access:0},
];

var result = [...arrA, ...arrB].reduce((acc, item) => { 
    return item;
 }) ;

arrA.concat(result)

//How would you do for the output to be

/*[
{language:'php', count_access:5},
{language:'c', count_access:7},
{language:'python', count_access:0},
{language:'ace', count_access:0},
{language:'electron', count_access:0},
]*/
Taffarel Xavier
  • 381
  • 5
  • 11

1 Answers1

2

This will work, it also adds up the counts for matching language

var arrA = [
    {language:'php', count:5},
    {language:'c', count:7}
];

var arrB = [
    {language:'php', count:0},
    {language:'c', count:0},
    {language:'python', count:0},
    {language:'ace', count:0},
    {language:'electron', count:0},
];

let result = [...arrA, ...arrB].reduce((acc, item) => {
  let found = acc.find(x => x.language=== item.language);
  if (found) {
    found.count += item.count;
  } else {
    acc.push(Object.assign({},item));
  }
  return acc;
}, [])
console.log(result);
Taffarel Xavier
  • 381
  • 5
  • 11
Bravo
  • 6,022
  • 1
  • 10
  • 15