简体   繁体   中英

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 .

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;
}

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM