0

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.

1
  • Can you use underscore.js? Commented Jul 21, 2015 at 17:51

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am currently using Coffeescript
1

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

Comments

1

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.

3 Comments

When using for..in in older IEs, be aware that each Array has an additional indexOf member.
Can you explain this line of code: return e[1] for e in a when e[0] == v ? Thanks
@connexo: CoffeeScript's for e in array is not the same as JavaScript's, JavaScript's in loop would be for k of object in CoffeeScript.
-1

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

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.