Skip to content

Instantly share code, notes, and snippets.

@vcanales
Last active January 22, 2020 03:53
Show Gist options
  • Save vcanales/3f4f2579e50e6100a9048956a44e1610 to your computer and use it in GitHub Desktop.
Save vcanales/3f4f2579e50e6100a9048956a44e1610 to your computer and use it in GitHub Desktop.
Given an array of objects, check if for any member, the pair `key`, `value` exists
const readableExists = (array, key, value) => array.reduce((acc, obj) => {
if (obj[key] && obj[key] === value) {
return true;
}
return acc;
}, false);
const cleverExists = (array, key, value) => array.reduce((acc, obj) => {
return obj[key] && obj[key] === value || acc;
}, false);
const someExists = (array, key, value) => array.some(obj => obj[key] && obj[key] === value);
const objects = [
{ name: 'John', age: 23 },
{ name: 'Maria', age: 29 },
{ name: 'Ian', age: 12 },
];
readableExists(objects, 'name', 'John');
// => true
cleverExists(objects, 'age', 24);
// => false
readableExists(objects, 'city', 'Santiago');
// => false
someExists(objects, 'age', 12);
// => true
someExists(object, 'someKey', true);
// => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment