5

I have a simple question. I have two arrays A and B, I want to retain A objects if B has the same ID. For example:

const A = [{id: "price", value: "1"}] const B = [{id: "price", value: "0"}, {id: "number", value: "0"}] 

Expected result:

[{id: "price", value: "1"}, {id: "number", value: "0"}}] 

How can I do this?

I tried to map A and foreach B inside A but it didn't work.

8
  • Do you want to replace A's objects or B's objects? The expected result is confusing Commented May 9, 2019 at 1:24
  • The term is "merging" and has been covered plenty of times... Commented May 9, 2019 at 1:24
  • I have edit. Thats right, I want to merge these two arrays into one Commented May 9, 2019 at 1:25
  • If A and B have same ID, do you want to keep A or B? Your question does not match your expected result. Commented May 9, 2019 at 1:26
  • 2
    Possible duplicate of es6 merge two array of objects and override the existing object Commented May 9, 2019 at 1:27

3 Answers 3

8
const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id))); 

Concatenate all the objects from A with objects from B that aren't in A (which is done by filtering only objects from B where there isn't an object in A with the same id).

Example:

const A = [{id: "price", value: "1"}]; const B = [{id: "price", value: "0"}, {id: "number", value: "0"}]; const result = A.concat(B.filter(bo => A.every(ao => ao.id != bo.id))); console.log(result);

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

Comments

1

You'd use reduce on the merged array - also turn the value into a number:

const A = [{id: "price", value: "1"}]; const B = [{id: "price", value: "0"}, {id: "number", value: "0"}]; const res = Object.values([...A, ...B].reduce((acc, { id, value }) => { if (acc[id]) acc[id].value += parseInt(value); else acc[id] = { id, value: parseInt(value) }; return acc; }, {})); console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

3 Comments

The problem is that my value is not always a number.
Well then what will your value be? A decimal?
It can be a number or a string. I want to replace
0

Another option that you could try (I believe it would be O(n) ) is to convert arrays to objects with id as key then extend (jquery.extend or pure js implementation) then convert the merged object back to array.

const A = [{id: "price", value: "1"}]; const B = [{id: "price", value: "0"}, {id: "number", value: "0"}]; //convert arrays to objects var Bx = {}; B.forEach(i => Bx[i.id] = i); var Ax = {}; A.forEach(i => Ax[i.id] = i); //copy all matching id properties from A to B A.forEach(i => Bx[i.id] = Ax[i.id]); //convert the merged object to array var C = []; Object.getOwnPropertyNames(Bx).forEach(i => C.push(Bx[i])); console.log(C);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.