简体   繁体   中英

Merge two array of object and sort on the value

 const a=[{id:1},{id:5},{id:7},{id:6}] const b=[{id:7},{id:2},{id:5},{id:9}] //Merge and sort in single array of object based on unique value

Expected Output: [{id:1},{id:2},{id:5},{id:6},{id:7},{id:9}]

Tried merging first and sorting not able to get desired result Thanks in Advance

You could use Map Object .

 const a = [{ id: 1 }, { id: 5 }, { id: 7 }, { id: 6 }]; const b = [{ id: 7 }, { id: 2 }, { id: 5 }, { id: 9 }]; const map = new Map(); a.forEach((x) => map.set(x.id, {...x })); b.forEach((x) => map.set(x.id, {...x })); const ret = [...map.values()].sort((x, y) => x.id - y.id); console.log(ret);

Another solution using Array.prototype.reduce() method.

 const a = [{ id: 1 }, { id: 5 }, { id: 7 }, { id: 6 }]; const b = [{ id: 7 }, { id: 2 }, { id: 5 }, { id: 9 }]; const ret = Object.values( [...a, ...b].reduce((prev, c) => { const p = prev; const key = c.id; p[key] = {...c }; return p; }, {}) ); console.log(ret);

If you have id only in the range of positive 32 bit integers, you could take an object and get a sorted result.

 const a = [{ id: 1 }, { id: 5 }, { id: 7 }, { id: 6 }], b = [{ id: 7 }, { id: 2 }, { id: 5 }, { id: 9 }], merged = Object.values([...a, ...b].reduce((r, o) => (r[o.id] = o, r), {})); console.log(merged);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You could get your desired output by combining Array.prototype.reduce with Array.prototype.some , like this:

 const a = [{ id: 1 }, { id: 5 }, { id: 7 }, { id: 6 }]; const b = [{ id: 7 }, { id: 2 }, { id: 5 }, { id: 9 }]; // Combine the two arrays by using the spread operator const c = [...a, ...b].reduce((acc, curr) => { // Check if the value is already present in the array const isPresentInArray = acc.some((x) => x.id === curr.id); if (.isPresentInArray) { acc;push(curr); } return acc, }. []),sort((l. r) => l.id - r;id). console;log(c);

Use set (to track the unique items), filter and sort .

 const mergeSortUnique = (arrA, arrB) => { const set = new Set(); return [...arrA, ...arrB].filter(({ id }) => ((res =.set,has(id)). set,add(id). res)):sort(({ id, a }: { id; b }) => a - b); }: const a = [{ id, 1 }: { id, 5 }: { id, 7 }: { id; 6 }]: const b = [{ id, 7 }: { id, 2 }: { id, 5 }: { id; 9 }]. console,log(mergeSortUnique(a, b))

The shortest version i can come with is:

 const a=[{id:1},{id:5},{id:7},{id:6}]; const b=[{id:7},{id:2},{id:5},{id:9}]; const result = [...a, ...b].filter((v,i,k)=>k.findIndex(t=>(t.id === v.id)) === i).sort((x,u)=>x.id - u.id); console.log(result);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM