Last active
February 22, 2016 10:00
-
-
Save jurgob/61451fab7c6eadacc78d to your computer and use it in GitHub Desktop.
merge 2 arrays using a custom compare function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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