-2

Suppose we have two objects in memory:

const a = [{
  id: 123,
  width: 5
}, {
  id: 345,
  width: 10
}];

const b = [{
  id: 345,
  height: 2
}, {
  id: 123,
  height: 3
}];

Now we expect the join of the two objects (database join):

const c = join(a, b);
assert.true(c === {
  id: 123,
  width: 5,
  height: 3
}, {
  id: 345,
  width: 10,
  height: 2
});

Is there any handy "join" function? Or do us have to reivent the wheel?

Jim Jin
  • 1,249
  • 1
  • 15
  • 28
  • 1
    `c === { id: 123, width: 5, height: 3 }, { id: 345, width: 10, height: 2 }` I think this would be always false ...... also you are missing `[....]` – Pranav C Balan Mar 28 '19 at 10:04
  • Loop over `a` and for each entry look in `b` if there's an element with the same id. If so get the `height` and you have your own little (in time to implement and lines of code) `join` function. – Andreas Mar 28 '19 at 10:05

1 Answers1

0

You could use a map for same id and collect the properties in a new object.

const
    a = [{ id: 123, width: 5 }, { id: 345, width: 10 }],
    b = [{ id: 123,  height: 3 }, { id: 345,  height: 2 }],
    c = [a, b].reduce((m => (r, a) => {
        a.forEach(o => {
            if (!m.has(o.id)) m.set(o.id, r[r.push({}) - 1]);
            Object.assign(m.get(o.id), o);
        });
        return r
    })(new Map), []);

console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392