-3

Suppose I have the following array:

var users = [
    {id: 3, name: "sally"}
    {id: 5, name: "bob"}
    {id: 40, name: "joe"}
    {id: 67, name: "eve"}
    {id: 168, name: "bob"}
    {id: 269, name: "amanda"}
]

I need to run a loadash function that would return true if, for example name == "bob" exists in the array regardless of how many times it exists in the array.

I would like to know is if there is one function I could use, possible using lodash (not necessarily though) that would return true or false indicating the existence of an object in the target array.

Thanks

Adam
  • 3,815
  • 29
  • 24
user3808307
  • 2,270
  • 9
  • 45
  • 99
  • 2
    This is very unclear. The title for instance says "get true *or* false", the question only says "return true". Given the array you provide, what is the output you expect? I'm probably not going out on a limb saying you will probably want to use either `map` or `filter`. If you just want to know if "bob" is in the array whatsoever, `some` will work (or `_.find`) – Dexygen Nov 25 '17 at 00:57
  • 1
    In lodash `_.find(users, ['name', 'Bob"]);` – charlietfl Nov 25 '17 at 00:59
  • 1
    Using native JS: `var test = users.some(u => u.name === "bob");`. – ibrahim mahrir Nov 25 '17 at 01:03
  • @George Jempty I only need it to return true. I guess find is the correct answer. – user3808307 Nov 25 '17 at 01:06
  • 1
    @user3808307 See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some – Dexygen Nov 25 '17 at 01:09
  • 1
    Using lodash: `var test = _.some(users, ["name", "bob"]);`. – ibrahim mahrir Nov 25 '17 at 01:10
  • Thank you @ibrahim mahrir! I guess some is better than find. That is exactly what I was looking for – user3808307 Nov 25 '17 at 01:24
  • 1
    You're welcome! I've added a lodash way too. I recommend you use lodash's version as you are already using it. – ibrahim mahrir Nov 25 '17 at 01:29

1 Answers1

2

You can use the filter function to search through your array and find the object with the given name.

var users = [
    {id: 3, name: "sally"},
    {id: 5, name: "bob"},
    {id: 40, name: "joe"},
    {id: 67, name: "eve"},
    {id: 168, name: "bob"},
    {id: 269, name: "amanda"},
];

function find(name) {
    return !!users.find(x => x.name === name);
}

More about the filter function can be found here

ztadic91
  • 2,774
  • 1
  • 15
  • 21