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 minutesAardvark found someone who knows about JavaScript
Gabriel G.22 / M / Londrina - PR, BRWhat do you mean by "exact location"?Friend 1M / Overland Park, KSsay 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]
Gabriel G.22 / M / Londrina - PR, BRI'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 1M / Overland Park, KSThanks Gabriel, I prototyped it http://pastie.org/761598 you rock!
Gabriel G.22 / M / Londrina - PR, BRCool, 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