Используя современный Javascript, вы можете использовать объект Map
для решения этой проблемы.
const array1 = [
{id: "14", text: "Notice 14"},
{id: "13", text: "Notice 13"},
{id: "12", text: "Notice 12"},
{id: "11", text: "Notice 11"},
{id: "10", text: "Notice 10"}
];
const array2 = [
{id: "11", text: "Notice 11a"},
{id: "14", text: "Notice 14a"},
{id: "12", text: "Notice 12"},
{id: "15", text: "Notice 15"}
];
function merge(arr1, arr2) {
// Use a Map to map objects by Id
const map = new Map();
arr1.forEach(e => map.set(e.id, e));
arr2.forEach(e => map.set(e.id, e));
// Create an empty array and populate it with the map entries
const result = [];
map.forEach( (value, key, map) => result.push(value));
// Sort by ID desc
result.sort((a, b) => a.id < b.id);
return result;
}
console.log(merge(array1, array2));
Это печатает:
[ { id: '15', text: 'Notice 15' },
{ id: '14', text: 'Notice 14a' },
{ id: '13', text: 'Notice 13' },
{ id: '12', text: 'Notice 12' },
{ id: '11', text: 'Notice 11a' },
{ id: '10', text: 'Notice 10' } ]