Reputation: 2105
Lets have a look at an example.
var arr1 = new Array({name: "lang", value: "English"},
{name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'},
{name: "lang", value: "German"});
I need to merge those 2 arrays of objects and create the following array:
var arr3 = new Array({name: "lang", value: "German"},
{name: "age", value: "18"},
{name : "childs", value: '5'});
Is there any JavaScript or jQuery function to do this?
$.extend
doesn't suit me. It returns
var arr4 = new Array({name : "childs", value: '5'},
{name: "lang", value: "German"});
Upvotes: 208
Views: 578461
Reputation: 351359
Weird that many answers do not take the uniqueness requirement into consideration, or if they do, use an inefficient algorithm to detect duplicates.
Use a Map to ensure uniqueness of whatever the key is:
const arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
const arr2 = [{name : "childs", value: '5'},{name: "lang", value: "German"}];
const arr3 = [...new Map(arr1.concat(arr2).map(o => [o.name, o])).values()];
console.log(arr3);
Upvotes: 0
Reputation: 139
this works for me:
const array1 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const array2 = [{ id: 2, name: 'Charlie' }, { id: 3, name: 'David' }];
const mergedArray = [...array1];
array2.forEach(obj => {
const existingObj = mergedArray.find(item => item.id === obj.id);
if (!existingObj) {
mergedArray.push(obj);
} else {
// Merge properties if needed
Object.assign(existingObj, obj);
}
});
console.log(mergedArray);
Upvotes: 0
Reputation: 1
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
function merge_by_property(arr1, arr2, prop) {
return arr2.reduce((accumulator, current) => {
const index = accumulator.findIndex(arr1index => arr1index[prop] == current[prop]);
if (index == -1) {
accumulator.push(current);
} else {
accumulator[index] = { ...accumulator[index], ...current }
}
return accumulator;
}, arr1);
}
const arr = merge_by_property(arr1, arr2, 'name');
// output : [
// { name: 'lang', value: 'German' },
// { name: 'age', value: '18' },
// { name: 'childs', value: '5' }
// ]
Using reduce and findindex
. also merging all properties on both element on the list.
Upvotes: 0
Reputation: 25
// simply like this
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
const obj1 = arr2[1];
const obj2 = arr1[1];
const obj3 = arr2[0];
const result = [obj1, obj2, obj3];
// or
let arr = [...arr2];
for (let x = 0; x < arr2.length; x++) {
arr1.sort((a, b) => a.name.localeCompare(b.name));
arr2.sort((a, b) => a.name.localeCompare(b.name));
if (arr2[x].name !== arr1[x].name) {
arr.push(arr1[x]);
}
}
Upvotes: 0
Reputation: 16543
for
loopconst merge = (first, second) => {
for(let i=0; i<second.length; i++) {
first.push(second[i]);
}
return first;
}
console.log(merge([1,2,3], [4,5,6])); // [1,2,3,4,5,6]
console.log(merge(merge([1,2,3], [4,5,6]), [7,8,9])); // [1,2,3,4,5,6,7,8,9]
Spread
operatorconst arr1 = [1,2,3];
const arr2 = [4,5,6];
// Merge arrays
const merged = [...arr1, ...arr2];
console.log(merged); // [1,2,3,4,5,6]
concat()
array methodconst arr1 = [1,2,3];
const arr2 = [4,5,6];
// Merge arrays
const merged1 = arr1.concat(arr2); // bit confusing, seems like `arr1` itself is being modified but it's not
const merged2 = [].concat(arr1, arr2); // cleaner approach
console.log(merged1); // [1,2,3,4,5,6]
console.log(merged2); // [1,2,3,4,5,6]
push()
array methodconst arr1A = [1,2,3];
const arr2A = [4,5,6];
const arr1B = [1,2,3];
const arr2B = [4,5,6];
const arr1C = [1,2,3];
const arr2C = [4,5,6];
const arr3C = [7,8,9];
// Merge arrays
const merged1 = arr1A.push(...arr2A);
// Merging without the ... on arr2B
const merged2 = arr1B.push(arr2B);
// Merge more than two arrays
arr1C.push(...[...arr2C, ...arr3C]);
console.log(arr1C); // [1,2,3,4,5,6,7,8,9]
console.log(merged1); // 6
console.log(arr1A); // [1,2,3,4,5,6]
console.log(arr2A); // [4,5,6]
console.log(merged2); // 4
console.log(arr1B); // [1,2,3,[4,5,6]]
console.log(arr2B); // [4,5,6]
reduce()
array methodconst arr1 = [1,2,3];
const arr2 = [4,5,6];
const merged = arr2.reduce((arr, item) => {
arr.push(item);
return arr;
}, arr1);
console.log(merged); // [1,2,3,4,5,6]
To Summarize,
spread
operator or the concat()
method is the most optimal solution.concat()
method.push()
method to merge arrays when you want to change one of the input arrays to merge.reduce()
method to merge arrays is a bit of overhead.For more info refer the detailed blog here and video here
Upvotes: 3
Reputation: 593
If you want to merge 2 arrays of objects in JavaScript, you can use for...of like this:
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
for (const x of arr2){ arr1.push(x); }
console.log(arr1);
Upvotes: 0
Reputation: 101
Highest voted responses did not meet the requirements, @Diogo Alves and @Pietro's answer is right, but you need to be careful with the order.
Upvotes: 0
Reputation: 8005
For those who are experimenting with modern things:
var odd = [{
name: "1",
arr: "in odd"
},
{
name: "3",
arr: "in odd"
}
];
var even = [{
name: "1",
arr: "in even"
},
{
name: "2",
arr: "in even"
},
{
name: "4",
arr: "in even"
}
];
// ----
// ES5 using Array.filter and Array.find
function merge(a, b, prop) {
var reduced = a.filter(function(aitem) {
return !b.find(function(bitem) {
return aitem[prop] === bitem[prop];
});
});
return reduced.concat(b);
}
console.log("ES5", merge(odd, even, "name"));
// ----
// ES6 arrow functions
function merge(a, b, prop) {
var reduced = a.filter(aitem => !b.find(bitem => aitem[prop] === bitem[prop]))
return reduced.concat(b);
}
console.log("ES6", merge(odd, even, "name"));
// ----
// ES6 one-liner
var merge = (a, b, p) => a.filter(aa => !b.find(bb => aa[p] === bb[p])).concat(b);
console.log("ES6 one-liner", merge(odd, even, "name"));
// Results
// ( stuff in the "b" array replaces things in the "a" array )
// [
// {
// "name": "3",
// "arr": "in odd"
// },
// {
// "name": "1",
// "arr": "in even"
// },
// {
// "name": "2",
// "arr": "in even"
// },
// {
// "name": "4",
// "arr": "in even"
// }
// ]
// for posterity, here's the old skool version
function merge(a, b, prop) {
var reduced = [];
for (var i = 0; i < a.length; i++) {
var aitem = a[i];
var found = false;
for (var ii = 0; ii < b.length; ii++) {
if (aitem[prop] === b[ii][prop]) {
found = true;
break;
}
}
if (!found) {
reduced.push(aitem);
}
}
return reduced.concat(b);
}
Upvotes: 56
Reputation: 1764
Based on the question, I understand that there is a key
that you want to use to override other attributes, not to merge them.
interface Foo {
name: string;
value: string;
}
var arr1: Foo[] = [
{ name: "lang", value: "English" },
{ name: "age", value: "18" },
];
var arr2: Foo[] = [
{ name: "childs", value: "5" },
{ name: "lang", value: "German" },
];
We can use combination of Map
with Reduce
to select the key
that will be used to overwrite the record.
const merged: Foo[] = Array.from(
[...arr1, ...arr2].reduce(
(acc, curr) => acc.set(curr.name, curr),
new Map<Foo["name"], Foo>(),
)
.values(),
);
// [
// { name: "lang", value: "German" },
// { name: "age", value: "18" },
// { name: "childs", value: "5" },
// ];
Upvotes: 1
Reputation: 11
Just use helprjs
const arr1 = [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jack'}];
const arr2 = [{ id: 2, name: 'Jane'}, { id: 3, name: 'Rod'}];
mergeArrays(arr1, arr2, "name");
// [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jane'}, { id: 3, name: 'Rod'}];
mergeArrays(arr1, arr2, "id");
// [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jack'}, { id: 3, name: 'Rod'}];
Check out the demo
Upvotes: 1
Reputation: 797
const arr1 = [{ name: "lang", value: "English" }, { name: "age", value: "18" }];
const arr2 = [{ name: "childs", value: '5' }, { name: "lang", value: "German" }];
const mergeArrOfObjects = (dataset1, dataset2) => {
const map1 = new Map();
dataset1.map((d1, i) => {
map1.set(d1.name, i);
})
for (let d2 of dataset2) {
if (d2 && map1.has(d2.name)) {
dataset1[map1.get(d2.name)] = d2;
} else if(d2){
dataset1.push(d2);
}
}
return dataset1;
};
const arr3 = mergeArrOfObjects(arr1, arr2);
console.log(arr3);
Upvotes: 1
Reputation: 12216
// no need new Array constructor, just using an array literal
const arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
const arr2 = [{name: "childs", value: '5'}, {name: "lang", value: "German"}];
// 1. create a map
const map = new Map();
// 2. concat array
// arr1.concat(arr2) === [...arr1, ...arr2]
const arr3 = [...arr1, ...arr2];
// 3. for ... of, iterator array
for(const obj of arr3) {
if(!map.has(obj.name)) {
// add
map.set(obj.name, obj);
} else {
// update
map.set(obj.name, {
...map.get(obj.name),
...obj,
});
}
}
// 4. get new merged unqiue array
const arr4 = [...map.values()];
console.log(`result array =`, JSON.stringify(arr4, null, 4));
/*
result array = [
{
"name": "lang",
"value": "German"
},
{
"name": "age",
"value": "18"
},
{
"name": "childs",
"value": "5"
}
]
*/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals
Upvotes: 6
Reputation: 33
//No need for using libraries and so on..
//You can just do
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
const arr3 = arr1.concat(arr2);
console.log(arr3); // final merged result will be in arr3
Upvotes: -1
Reputation: 27559
I'd merge two arrays with duplicates and then use my this answer to remove duplicates. This looks like shortest way.
const arr1 = [{
name: "lang",
value: "English"
},
{
name: "age",
value: "18"
}
];
const arr2 = [{
name: "childs",
value: '5'
},
{
name: "lang",
value: "German"
}
];
const mergedArray = [...arr1, ...arr2];
const uniqueData = [...mergedArray.reduce((map, obj) => map.set(obj.name, obj), new Map()).values()];
console.log(uniqueData)
Upvotes: 15
Reputation: 506
var arr1 = [{ name: "lang", value: "English" }, { name: "age", value: "18" }];
var arr2 = [{ name: "childs", value: '5' }, { name: "lang", value: "German" }];
function mergeArrayByProperty(arr1, arr2, prop) {
var newArray =
arr1.map(item => {
if (typeof (item[prop]) !== "undefined") {
var nItems = arr2.filter(ni => { if (typeof (ni[prop]) !== "undefined" && ni[prop] === item[prop]) return ni; });
if (nItems.length > 0) {
item = Object.assign({}, item, nItems[0]);
}
return item;
}
});
var arr2nd = arr2.flatMap(item => { return item[prop] });
var arr1nd = arr1.flatMap(item => { return item[prop] });
var nonDupArr = arr2nd.map(p => { if (arr1nd.includes(p) === false) return arr2.filter(i2 => { if (i2[prop] === p) return Object.assign({}, i2) })[0]; });
return newArray.concat(nonDupArr).filter(i=>{if(i !== null)return i})
}
var arr = mergeArrayByProperty(arr1, arr2, 'name');
console.log(arr)
This finds the duplicate key in the first array and merges the second arrays object having the same key value. If no value is found in the second array, it uses the original object. As you can see, lang is only found once in the result set; having german for the value.
Upvotes: 2
Reputation: 1638
Solution utilizing JS Map:
const merge = (arr1, arr2, prop) => {
const resultMap = new Map(arr1.map((item) => [item[prop], item]));
arr2.forEach((item) => {
const mapItem = resultMap.get(item[prop]);
if (mapItem) Object.assign(mapItem, item);
else resultMap.set(item[prop], item);
});
return [...resultMap.values()];
};
const arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
const arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
console.log(merge(arr1, arr2, "name"));
Which produces:
Upvotes: 4
Reputation: 5145
Posting this because unlike the previous answers this one is generic, no external libraries, O(n), actually filters out the duplicate and keeps the order the OP is asking for (by placing the last matching element in place of first appearance):
function unique(array, keyfunc) {
return array.reduce((result, entry) => {
const key = keyfunc(entry)
if(key in result.seen) {
result.array[result.seen[key]] = entry
} else {
result.seen[key] = result.array.length
result.array.push(entry)
}
return result
}, { array: [], seen: {}}).array
}
Usage:
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"})
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"})
var arr3 = unique([...arr1, ...arr2], x => x.name)
/* arr3 == [
{name: "lang", value: "German"},
{name: "age", value: "18"},
{name: "childs", value: "5"}
]*/
Upvotes: 1
Reputation: 464
You can leverage hash maps and Object.values
to accomplish this in roughly O(3n) time. This looks like O(n^2), but the outer loop is just to iterate through the arrays to be merged.
function uniqueMerge(arrays) {
const results = {};
arrays.forEach((arr) => {
arr.forEach(item => {
results[item.name] = item;
});
});
return Object.values(results);
}
Upvotes: 0
Reputation: 139
let mergeArray = arrA.filter(aItem => !arrB.find(bItem => aItem.name === bItem.name))
Upvotes: 1
Reputation: 31
const array1 = [{id:1,name:'ganza'},
{id:2,name:'respice dddd'},{id:4,name:'respice dddd'},{id:6,name:'respice dddd'},
{id:7,name:'respice dddd'}];
const array2 = [{id:1,name:'ganza respice'},{id:2,name:'respice'},{id:3,name:'mg'}];
function mergeTwoArray(array1,array2){
return array1.map((item,i)=>{
if(array2[i] && item.id===array2[i].id){
return array2[i];
}else{
return item;
}
});
}
const result = mergeTwoArray(array1,array2);
console.log(result);
//here is the result: Array [Object { id: 1, name: "ganza respice" },
Object { id: 2, name: "respice" }, Object { id: 4, name: "respice dddd" },
Object { id: 6, name: "respice dddd" }, Object { id: 7, name: "respice dddd" }]
Upvotes: 0
Reputation: 31
const array1 = [{id:1,name:'ganza'},
{id:2,name:'respice dddd'},{id:4,name:'respice dddd'},{id:6,name:'respice dddd'},
{id:7,name:'respice dddd'}];
const array2 = [{id:1,name:'ganza respice'},{id:2,name:'respice'},{id:3,name:'mg'}];
function mergeTwoArray(array1,array2){
return array1.map((item,i)=>{
if(array2[i] && item.id===array2[i].id){
return array2[i];
}else{
return item;
}
});
}
const result = merge(array1,array2);
console.log(result);
//here is the result: Array [Object { id: 1, name: "ganza respice" }, Object { id: 2, name: "respice" }, Object { id: 4, name: "respice dddd" }, Object { id: 6, name: "respice dddd" }, Object { id: 7, name: "respice dddd" }]
Upvotes: 0
Reputation: 4450
Very simple using ES6 spread operator:
const array1 = [{a: 'HI!'}, {b: 'HOW'}]
const array2 = [{c: 'ARE'}, {d: 'YOU?'}]
const mergedArray = [ ...array1, ...array2 ]
console.log('Merged Array: ', mergedArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Merged Array: [ {a: 'HI!'}, {b: 'HOW'} {c: 'ARE'}, {d: 'YOU?'} ]
Note: The above solution is to just merge two arrays using ES6 spread operator.
Edit on 07 January 2020 by @bh4r4th : As the context changed due to edits after my initial solution. I would like to update my solution to match current criteria. i.e.,
Merger array objects without creating duplicate objects and,
update the value
if the name
property already exists in the prior array
const arr1 = [
{ name: "lang", value: "English" },
{ name: "age", value: "18" }
]
const arr2 = [
{ name: "childs", value: '2' },
{ name: "lang", value: "German" }
]
const arr3 = [
{ name: "lang", value: "German" },
{ name: "age", value: "28" },
{ name: "childs", value: '5' }
]
// Convert to key value dictionary or object
const convertToKeyValueDict = arrayObj => {
const val = {}
arrayObj.forEach(ob => {
val[ob.name] = ob.value
})
return val
}
// update or merge array
const updateOrMerge = (a1, a2) => {
const ob1 = convertToKeyValueDict(a1)
const ob2 = convertToKeyValueDict(a2)
// Note: Spread operator with objects used here
const merged_obj = {...ob1, ...ob2}
const val = Object.entries(merged_obj)
return val.map(obj => ({ name: obj[0], value: obj[1] }))
}
const v1 = updateOrMerge(arr1, arr2)
const v2 = updateOrMerge(v1, arr3)
console.log(`Merged array1 and array2: ${JSON.stringify(v1)} \n\n`)
console.log(`Merged above response and array3: ${JSON.stringify(v2)} \n\n`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upvotes: 46
Reputation: 5260
const mergeByProperty = (target, source, prop) => {
source.forEach(sourceElement => {
let targetElement = target.find(targetElement => {
return sourceElement[prop] === targetElement[prop];
})
targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement);
})
}
var target /* arr1 */ = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var source /* arr2 */ = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
mergeByProperty(target, source, 'name');
console.log(target)
This answer was getting old, libs like lodash and underscore are much less needed these days. In this new version, the target (arr1) array is the one we’re working with and want to keep up to date. The source (arr2) array is where the new data is coming from, and we want it merged into our target array.
We loop over the source array looking for new data, and for every object that is not yet found in our target array we simply add that object using target.push(sourceElement) If, based on our key property ('name'), an object is already in our target array - we update its properties and values using Object.assign(targetElement, sourceElement). Our “target” will always be the same array and with updated content.
I always arrive here from google and I'm always not satisfy from the answers. YOU answer is good but it'll be easier and neater using underscore.js
DEMO: http://jsfiddle.net/guya/eAWKR/
Here is a more general function that will merge 2 arrays using a property of their objects. In this case the property is 'name'
var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
function mergeByProperty(arr1, arr2, prop) {
_.each(arr2, function(arr2obj) {
var arr1obj = _.find(arr1, function(arr1obj) {
return arr1obj[prop] === arr2obj[prop];
});
arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj);
});
}
mergeByProperty(arr1, arr2, 'name');
console.log(arr1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>
[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
Upvotes: 54
Reputation: 41
const arr1 = ["Vijendra","Singh"];
const arr2 = ["Singh", "Shakya"];
arr2.forEach(item => {
if(!arr1.find(k => k===item))
arr1.push(item)
});
console.log(arr1)
Upvotes: 0
Reputation: 4076
Try this:
var a = [{"a":20, "b":10,"c":"c","d":"asd","f":"any"}]
var b = [{"a":20, "b":10,"c":"c", "e":"nan","g":10200}]
var p = []
_.map(a, function(da){
var chk = _.filter(b, function(ds){
return da.a ===ds.a
})[0]
p.push(_.extend(da, chk))
})
console.log(p)
OutPut will be :
[{
"a": 20,
"b": 10,
"c": "c",
"d": "asd",
"f": "any",
"e": "nan",
"g": 10200
}]
Upvotes: 0
Reputation: 347
If you want to merge the 2 arrays, but remove duplicate objects use this.
Duplicates are identified on .uniqueId
of each object
function mergeObjectArraysRemovingDuplicates(firstObjectArray, secondObjectArray) {
return firstObjectArray.concat(
secondObjectArray.filter((object) => !firstObjectArray.map((x) => x.uniqueId).includes(object.uniqueId)),
);
}
Upvotes: 0
Reputation: 1009
With ES6 you can do it very easy as below:
var arr1 = new Array({name: "lang", value: "German"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var arr3 = [...arr1, ...arr2];
Output:
arr3 = [
{"name":"lang","value":"German"},
{"name":"age","value":"18"},
{"name":"childs","value":"5"},
{"name":"lang","value":"German"}
]
Upvotes: 75
Reputation: 5272
Simple solution
var tx = [{"id":1},{"id":2}];
var tx1 = [{"id":3},{"id":4}];
var txHistory = tx.concat(tx1)
console.log(txHistory);
// output
// [{"id":1},{"id":2},{"id":3},{"id":4}];
Upvotes: 5
Reputation: 111
you could use following function
const merge = (a, b, key = "id") =>
a.filter(elem => !b.find(subElem => subElem[key] === elem[key]))
.concat(b);
and try
merge(arr1, arr2, 'name');
Upvotes: 3
Reputation: 61
merge(a, b, key) {
let merged = [];
a.forEach(aitem => {
let found = b.find( bitem => aitem[key] === bitem[key]);
merged.push(found? found: aitem);
});
return merged;
}
Upvotes: 0