Skip to content

Instantly share code, notes, and snippets.

@diegomais
Created January 22, 2021 17:39
Show Gist options
  • Save diegomais/788ff5974900ccdf6edb3520719fbd02 to your computer and use it in GitHub Desktop.
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
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;
}
@diegomais
Copy link
Author

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' } ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment