Created
January 22, 2021 17:39
-
-
Save diegomais/788ff5974900ccdf6edb3520719fbd02 to your computer and use it in GitHub Desktop.
Filter by object key an array containing objects based on another array containing objects in JavaScript without ES6
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
function filterArraysByKey (arr1, arr2, key) { | |
var result = []; | |
result = arr1.filter(function (el) { | |
var res = true; | |
for (var i = arr2.length - 1; i >= 0; i--) { | |
if (arr2[i][key] === el[key]) { | |
res = false; | |
break; | |
} | |
} | |
return res; | |
}); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
console.log(filterArraysByKey(arr1, arr2, 'id')); // [ { id: '2', name: 'B' }, { id: '4', name: 'D' } ]