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
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
Share asked Jan 12, 2021 at 12:19 InfinityInfinity 931 silver badge12 bronze badges5 Answers
Reset to default 5You 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 bining 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 e 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);