Omar Lahlou
Omar Lahlou

Reputation: 1000

Find specific element in array javascript

I have an array A containing n arrays. Each of the n arrays, contains two element. The first is an id, while the second is an object. For more details, see the following example:

A = [ [100, object1], [22, object2], [300, object3]]

For a given id, I want to get the associated object. Example, for id = 22, I want to get object2.

Upvotes: 0

Views: 88

Answers (4)

mu is too short
mu is too short

Reputation: 434745

A CoffeeScript version could like:

find_in = (a, v) ->
    return e[1] for e in a when e[0] == v

then you could say:

thing = find_in(A, 22)

You'd get undefined if there was no v to be found.

The for e in a is a basic for-loop and then when clause only executes the body when its condition is true. So that loop is functionally equivalent to:

for e in a
    if e[0] == v
        return e[1]

The fine manual covers all this.

Upvotes: 1

Dev Singh
Dev Singh

Reputation: 71

In CoffeeScript you can use the JS to CF transition

getById = (id) ->
  i = 0
  while i < A.length
    if A[i][0] == id
      return A[i][1]
    i++
  false

Upvotes: -1

connexo
connexo

Reputation: 56773

This is a very basic way of doing it. Iterate over A, keep checking whether the first member of each array matches your id, and return the associated object in case of a match.

function returnObjectById(id) {
    for (var i=0; i< A.length; i++) {
        if (A[i][0]==id) {
            return A[i][1];
        }
    }
    return false; // in case id does not exist
}

In Coffeescript:

returnObjectById = (id) ->
  i = 0
  while i < A.length
    if A[i][0] == id
      return A[i][1]
    i++
  false
  # in case id does not exist

Upvotes: 1

tymeJV
tymeJV

Reputation: 104785

Loop, check, and return

function getById(id) {
    for (var i = 0; i < A.length; i++) {
        if (A[i][0] == id) {
            return A[i][1];
        }
    }
    return false;
}

Upvotes: 2

Related Questions