A
A
Anatoly2021-06-11 10:08:10
JavaScript
Anatoly, 2021-06-11 10:08:10

How to merge 2 objects and eliminate matches?

There are 2 objects:
let a = {"0": 1, "1": 2, "2": 3};
let b = {"0": 4, "1": 5, "2": 1};

How to merge and exclude identical values?
Desired result:
{"0": 1, "1": 2, "2": 3, "3": 4, "4": 5};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-06-11
@Tolly

According to the example:

const merge = (a, b) => {
  const combined = new Set([...Object.values(a), ...Object.values(b)]);
  
  return Object.fromEntries(
    [...combined.values()].map((value, index) => [index, value])
  );
};

merge(
  { "0": 1, "1": 2, "2": 3 },
  { "0": 4, "1": 5, "2": 1 }
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question