Last active
January 22, 2020 03:53
-
-
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
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
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