user1740381
user1740381

Reputation: 2199

Best way to search item in the javascript array

I have an array of objects in javascript. The objects contain some properties and look something like this :

  { "Name" : "blabla", "Id": "1" }

Now I have a function which accepts a single parameter that will be the Name property value of the object. The function looks somethings like this :

     function CheckForExistance(array, name){
       var exist = false;

       $.each(array, function(index, value){
          if(value.Name == name)
          {
             exist = true;
             return false;
          }
       });
       return exist;
     }

I want to know if there is a better way to do this ?

Upvotes: 0

Views: 2356

Answers (4)

I Hate Lazy
I Hate Lazy

Reputation: 48761

You can use $.grep() to filter down the array to a match, and return a comparison of the .length.

 function CheckForExistance(array, name){
     return $.grep(array, function(obj) {
         return obj.Name == name;
     }).length > 0;
 }

Or native methods are a little nicer IMO, but you'll need a shim for old browsers.

function CheckForExistance(array, name){
    return array.some(function(obj) {
        return obj.Name == name;
    });
}

This one uses Array.prototype.some, and will exit as soon as a truthy return value is given, and will then return true. If no truthy return is found, then it'll return false.


FWIW, you can make your function a little more robust by providing a dynamic property name as well.

function CheckForExistance(array, prop, val){
    return array.some(function(obj) {
        return obj[prop] == val;
    });
}

Then use it to check any property value.

var found = CheckForExistance(myArray, "Name", "blabla");

Or another approach would be to make a function factory that creates functions to be used with iterators.

function havePropValue(prop, value) {
    return function(obj) {
        return obj[prop] == value;
    };
}

Then we can just use .some() directly without needing the CheckForExistance function.

var found = myArray.some(havePropValue("Name", "blabla"));

Or with $.grep.

var found = $.grep(myArray, havePropValue("Name", "blabla")).length > 0;

Upvotes: 4

anche
anche

Reputation: 2884

This should work:

function CheckForExistance(array, name){
           var exist = false;
           $.each(array, function(index, value){
              if (value == name) {
                   exist = true;
              }
           });
           return exist;
         }

value.Name isn't a string. When looping trough an array you get an index and a value.

For example: array { 1: "foo", 2:"bar" } gives you index: 1, value: "foo" index: 2, value: "bar"

value is the one you want to compare to your variable 'name'.

2: You returned false after making 'exist' true. That will never give a 'return true'. After making 'exist' true you should return exist.

I think my code is what you're looking for.

Upvotes: -1

Anurag Uniyal
Anurag Uniyal

Reputation: 88727

If it is a simple array object why not just loop through it, instead of complicating it why to use $.each when plain JavaScript is simpler

 function CheckForExistance(array, name) {
   for(var i=0;i<array.length;i++){
     if(array[i].Name==name) return true;
   }
   return false;
 }

Upvotes: 2

Robin Drexler
Robin Drexler

Reputation: 4457

You could also use the native Array.fiter method to determine whether the object with Name x does exist or not. Filter returns a new array, containing all the elements, which are matching the callback function (return true). https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

If the length of the new array is greater than 0, than there is at least one matching element.

function checkForExistance(arrayOfItems, name) {
    return arrayOfItems.filter(function (item) {
        return item.Name === name;
    }).length > 0;

}


var arr = [{
    "Name": "blabla",
    "Id": "1"
}, {
    "Name": "foo",
    "Id": "2"
}]

console.log(checkForExistance(arr, "foo"));

http://jsfiddle.net/Uawrb/1/

This won't work in IE<9, but if you want it to work there too, you can check out jQuery's $.grep implementation, which should work cross-browser :)

function checkForExistance(arrayOfItems, name) {
    return $.grep(arrayOfItems, function (item) {
        return item.Name === name;
    }).length > 0;

}


var arr = [{
    "Name": "blabla",
    "Id": "1"
}, {
    "Name": "foo",
    "Id": "2"
}]

console.log(checkForExistance(arr, "foo"));​

http://jsfiddle.net/5vqqq/1/

Upvotes: 0

Related Questions