0

I'm trying to get a single Array with all values contained in arr1 and arr2. But I can't reach that final result.

arr1 = [
  {
    region: "Total",
    population: 15200100,
    first: 42999
  }
]

arr2 = [
  {
    region: "Total",
    second: 2939
  }
]

output = [
  {
    region: "Total",
    population: 15200100,
    first: 42999
    second: 2939
  }
]
1
  • um, btw in each arr all keys(things like region) WILL be unique? Commented Feb 20, 2021 at 20:01

3 Answers 3

1

In one line:

const arr1 = [ { region: "Total", population: 15200100, first: 42999 } ];
const arr2 = [ { region: "Total", second: 2939 } ];
const res = arr1.map((_, index) => ({ ...arr1[index], ...arr2[index] }));

console.log(res);

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

Comments

0

Try this:

const arr1 = [ { region: "Total", population: 15200100, first: 42999 } ];
const arr2 = [ { region: "Total", second: 2939 } ];
const res = [];

for(let i = 0; i < arr1.length || i < arr2.length; i++) {
  const first = arr1[i] || {};
  const second = arr2[i] || {};
  res[i] = { ...first, ...second };
}

console.log(res);

Comments

0

The example below returns a sum when similar keys are found.

const arr1 = [{
  region: "Total",
  population: 15200100,
  first: 42999
}];
const arr2 = [{
  region: "Total",
  second: 2939
}];
const arr3 = [{
  region: "Total",
  population: 15200100,
  first: 42999
}];
const arr4 = [{
  region: "Total",
  first: 3243,
  second: 2939,
  third: 32
}];
function test(arr1,arr2) {
  let res = Array.from(arr1);
  res.forEach((x) => {
    arr2.forEach((y) => {
      for (let key in y) {
        if (typeof x[key] == 'undefined') {
          x[key] = y[key];
        } else {
          if (key !== 'region') {
            x[key] += y[key];
          }
        }
      }
    });
  });
  return res;
}

console.log(test(arr1,arr2));
console.log(test(arr3,arr4));

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.