-2

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

8
  • 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) Commented Nov 25, 2017 at 0:57
  • 1
    In lodash _.find(users, ['name', 'Bob"]); Commented Nov 25, 2017 at 0:59
  • 1
    Using native JS: var test = users.some(u => u.name === "bob");. Commented Nov 25, 2017 at 1:03
  • 1
    @user3808307 See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 25, 2017 at 1:09
  • 1
    Using lodash: var test = _.some(users, ["name", "bob"]);. Commented Nov 25, 2017 at 1:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

you could add a bit explanation
@entio explain a bit further please
@entio i misunderstood your comment, added a link and basic explanation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.