Gabriel answered a question about *JavaScript* on Aardvark!

Question
Dec 30, 2009
Sent to Aardvark via web
Friend 1
M / Overland Park, KS
anyone know of a function to recursively search through a multidimensional javascript array and return the elementsd exact location?
  • Answer 1
    + 16 minutes
    Aardvark found someone who knows about JavaScript

    X0amjvra_1260697447
    Gabriel G.
    22 / M / Londrina - PR, BR
    Knows about: UEL

    13 Qs & As in last few weeks

    What do you mean by "exact location"?
    Friend 1
    M / Overland Park, KS
    say I had an array [4,10], if i search through it and the value is in the second dimension and in the 8th element it should return [1,8]
    X0amjvra_1260697447
    Gabriel G.
    22 / M / Londrina - PR, BR
    Knows about: UEL

    13 Qs & As in last few weeks

    I'll work something out, just a sec

    there you go function getPositionInMatrix(needle, haystack, pos) { pos = pos || []; for(var i = haystack.length; --i >= 0;) { if(haystack[i] === needle) { return pos.push(i); } else if(Object.prototype.toString.call(haystack[i]) === '[object Array]') { pos.push(i); if(getPositionInMatrix(needle, haystack[i], pos)) { return pos; } else { pos.pop(); } } } return false; }

    Aw, the code got all trimmed, I put it on pastie: http://pastie.org/761590

    Usage: js> getPositionInMatrix('foo', ['bar',['baz','foo'],'foobar']); [1,1]
    Friend 1
    M / Overland Park, KS
    Thanks Gabriel, I prototyped it http://pastie.org/761598 you rock!
    X0amjvra_1260697447
    Gabriel G.
    22 / M / Londrina - PR, BR
    Knows about: UEL

    13 Qs & As in last few weeks

    Cool, glad I could help!

What is Aardvark?

Aardvark discovers the perfect person in your network to answer any question in minutes.

How do I ask a question?

  • Just send Aardvark an IM, email or tweet with a question — or ask from vark.com
  • Aardvark will send you a response from someone in your network within minutes

Share this page

 
x