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},
]*/
11
  • 1
    I'd use reduce like let result = [...arrA, ...arrB].reduce((acc, item) => { code here }, []) ... that should be enough to get you to write something for yourself Commented Oct 29, 2019 at 1:55
  • var arrA = [ {nome:'php', count:5}, {nome:'c', count:7} ]; var arrB = [ {nome:'php', count:0}, {nome:'c', count:0}, {nome:'python', count:0}, ]; var result = [...arrA, ...arrB].reduce((acc, item) => { return item; }, []) ; arrA.concat(result) Commented Oct 29, 2019 at 2:00
  • really? that doesn't look right at all Commented Oct 29, 2019 at 2:01
  • It didn't work with more than three items in arrB Commented Oct 29, 2019 at 2:04
  • For example: var arrA = [ {nome:'php', count:5}, {nome:'c', count:7} ]; var arrB = [ {nome:'php', count:0}, {nome:'c', count:0}, {nome:'python', count:0}, {nome:'ace', count:0}, {nome:'electron', count:0}, ]; var result = [...arrA, ...arrB].reduce((acc, item) => { return item; }) ; arrA.concat(result) Commented Oct 29, 2019 at 2:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.