0

I have the following array:

var myArray = [
        {
            "id":1,
            "name":"name1",
            "resource_uri":"/api/v1/product/1"
        },
        {
            "id":5,
            "name":"name2",
            "resource_uri":"/api/v1/product/5"
        }
]

Each row is identified by it's unique id. I am quite new to Javascript and was wondering what was the best solution to find a cell based on id.

For example, for the id:5; my function must return:

findCell(myTable, id=5);
// this function must return:
{
     "id":5,
     "name":"name2",
     "resource_uri":"/api/v1/product/5"
}

I'm quite afraid to do an ugly for loop... Maybe there is some built-in javascript function to perform such basic operations.

Thanks.

Alex Grs
  • 3,231
  • 5
  • 39
  • 58
  • Does it need to be in an array? Why not store the ids as keys in an object? – David Weldon Sep 02 '13 at 17:20
  • possible duplicate of [How to get index of object by its property in javascript](http://stackoverflow.com/questions/7176908/how-to-get-index-of-object-by-its-property-in-javascript) – mbeckish Sep 02 '13 at 17:20
  • The title is misleading. You are searching an object in an array by a property. Check [this answer](http://stackoverflow.com/questions/5579678/jquery-how-to-find-an-object-by-attribute-in-an-array/15767679#15767679). – Luca Fagioli Sep 02 '13 at 17:21
  • Thank @LucaFagioli, it's answer work very well and without Javascript. The solution with filter is not the best for me as my id are unique. Sadly I can't change the output and put id as keys, it would have been a lot more easier though. – Alex Grs Sep 02 '13 at 17:33
  • @AlexGrs you can build a key => index map on the fly though... – dc5 Sep 02 '13 at 17:39
  • @Alex Grs, I'm glad it helped you. – Luca Fagioli Sep 02 '13 at 17:42

3 Answers3

2

Yes there is a built-in function - filter. I would use it like this:

findCells(table, property, value) {
   return table.filter(function (item) {
      return item[property] === value;
   });
}

findCells(myTable, "id", 5);

This is a bit modified version, of what you want: it can find all cells by the specified property name value.

Edit: using for loop to search the first occurence of the element is okay, actually:

findCell(table, id) {
   var result = null;
   for (var i = 0, cell = table[0], l = table.length; i < l; i++, cell = table[i]) {
      if (cell.id === id) {
         result = cell;
         break;
      }
   }
   return result;
}

findCell(myTable, 5);
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
  • Don't forget that this returns an array. You might want to check the length of the array and return either `null` or the element itself, if the property is unique. – Zeta Sep 02 '13 at 17:20
  • The filter function is when you want to filter an array. It will loop through all its values, it won't return when it finds what you are searching for. – Luca Fagioli Sep 02 '13 at 17:23
  • @LucaFagioli as I said, it is a slightly modified version to find any amount of cells by any property passed as a parameter. In my opinion it is more useful, than simply finding first element by `id`. – Artyom Neustroev Sep 02 '13 at 17:25
  • An **id** should be unique, so it is a wrong approach searching for two or more different objects with the same **id**. – Luca Fagioli Sep 02 '13 at 17:27
  • @LucaFagioli, sir, my function is not necessarily searches by **id**. But okay, I will update the answer. – Artyom Neustroev Sep 02 '13 at 17:29
0

Try this expression this might be helpful

var result = myArray.filter(function(element, index) { return element.ID == 5; });

filter() has two parameters

element - current row

index - current row index.

Sohil Desai
  • 2,940
  • 5
  • 23
  • 35
0

If you are going to stick with the array, the 'ugly' for loop is your best bet for compatibility. It's not that ugly when put in a function:

function findById(id) {
    for(var i = 0; i < myArray.length; ++i) {
        if(myArray[i].id === id) return myArray[i];
    }
}

// Not checking return value here!
alert(findById(5).name);

Filter is another option if your concern is only with recent versions of browsers. It will return an array of values.

If your array is very large though, it would make sense to introduce some sort of index for efficient lookups. It adds an additional maintenance burden, but can increase performance for frequent lookups:

var index = {};
for(var i = 0; i < myArray.length; ++i) {
    index[myArray[i].id] = i;
}

// Find element with id=5
alert(myArray[index[5]].name);

Example

dc5
  • 12,341
  • 2
  • 35
  • 47