Skip to content

Instantly share code, notes, and snippets.

@jurgob
Last active February 22, 2016 10:00
Show Gist options
  • Save jurgob/61451fab7c6eadacc78d to your computer and use it in GitHub Desktop.
Save jurgob/61451fab7c6eadacc78d to your computer and use it in GitHub Desktop.
merge 2 arrays using a custom compare function
function margeArrays(arr1,arr2,mergeFunc){
let arr2Temp = [...arr2];
const arrayMerged = arr1
.map((t) => {
const t1 = arr2Temp.filter((el,idx) => mergeFunc(t,el) && arr2Temp.splice(idx, 1) )[0]
return t1 ? t1 : t
})
.concat(arr2Temp);
return arrayMerged;
}
//EXAMPLE:
const arr1 = [
{id:"1",from:"arr1"},
{id:"2",from:"arr1"},
{id:"3",from:"arr1"}
]
const arr2 = [
{id:"1",from:"arr2"},
{id:"4",from:"arr2"},
{id:"5",from:"arr2"}
]
const mergeById = (t,t1) => t.id === t1.id
console.log('arrayMerged' ,margeArrays(arr1,arr2,mergeById));
/*it will return:
[
{id:"1",from:"arr2"},
{id:"2",from:"arr1"},
{id:"3",from:"arr1"},
{id:"4",from:"arr2"},
{id:"5",from:"arr2"}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment