Last active
August 11, 2021 19:51
-
-
Save rostegg/8c603832cc00317c8d93d1c04a03f20d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
Just experiments and some thoughts. | |
Better use for/foreach over arrays and check if target arr already contains objects, something like: | |
const target = [...one] | |
for (current of two) { | |
const duplicated = target.find(item => item.id === current.id); | |
!duplicated && target.push(current); | |
// choose which element to put into the array | |
if (duplicated && current.value > duplicated.value) | |
target[target.indexOf(duplicated)] = current; | |
} | |
*/ | |
const one = [ | |
{ id: 1, value: 11 }, | |
{ id: 2, value: 23 }, | |
{ id: 3, value: 42 }, //dup | |
{ id: 4, value: 21 }, //dup prior | |
] | |
const two = [ | |
{ id: 3, value: 55 }, //dup prior | |
{ id: 4, value: 5 }, //dup | |
{ id: 5, value: 123 }, | |
{ id: 6, value: 66 }, | |
] | |
const arr = [...one, ...two] | |
const compare = (o1, o2) => { return o1.value >= o2.value ? o1 : o2 } | |
function filterWithComparison(arr, compareFunc, key = 'id') { | |
return arr.reduce((acc, current) => { | |
function compareAndReplace(duplicated) { | |
const obj = compareFunc(current, duplicated); | |
acc[acc.indexOf(duplicated)] = obj; | |
} | |
//check | |
const duplicated = acc.find(item => item[key] === current[key]); | |
duplicated && compareAndReplace(duplicated); | |
return !duplicated ? [...acc, current ] : acc; | |
}, []); | |
} | |
const filtered = filterWithComparison(arr, compare) | |
console.log(filtered) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment