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.
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);
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; }
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.