0

I want to know whether the given value exists in javascript array or not.

Here is my case,

var array = [{'id': 1, 'name': 'xxx'},
         {'id': 2, 'name': 'yyy'},
         {'id': 3, 'name': 'zzz'}];

 var searchValue = {'id': 1, 'name': 'xxx'};

I tried the following,

var exists = _.where(array, {name: 'xxx'});

It return the obj {'id': 1, 'name': 'xxx'}. It works as expect.

Here I need to check exists.length > 0 to find whether it exists or not

But is there any other function of get the same.

Since if the function return true if exists and false if not, It would be better.

2
  • Can't you simply do _.where(array, {name: 'xxx'}).length > 0 Commented Feb 3, 2014 at 10:14
  • @Satpal: _.where has to find them all, _.find and _.findWhere will short-circuit and return as soon as they've found a match so they're more appropriate for existence checks. Commented Feb 3, 2014 at 18:00

3 Answers 3

9

It's the same idea, but would this do the trick ?

return !!_.findWhere(array, {name : 'xxx'});

Otherwise (but slighly longer)

return _.some(array, function (item) {
   return (item.name === "xxx");
});

Also, note that _.where and _.findWhere seems to be on the deprecation row ... And that as @Juzer Ali pointed out, you might not even need it if you're targeting modern enough browsers.

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

Comments

1

No need to use underscore. These days browsers have these idioms built in. See Array.some.

array.some(function(elem){
    return !!elem["name"] === "xxx";
});

From the docs

some does not mutate the array on which it is called.

6 Comments

Let's precise it doesn't work on IE8 because the main reason to use a library like underscore is precisely to be able to use modern functions on IE8-.
Wouldn't this return true if any element has an 'xxx' property ? I think the OP wants to check the value...
OP asked > (if) the function return true if exists and false if not, It would be better.
Yes, but I understood that as saying "I need a function that returns true or false", instead of "having a function that returns a list, and having to check the size of the list" ; but "exists" means "is an element with the name I want".
@phtrivier, Oops, thats what happens when you type faster than you think. I corrected my answer. Thanks.
|
1

Use isEmpty

var exists = !_.isEmpty(_.where(array, {name: 'xxx'}));

Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.