Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 18991  / 14 Years ago, tue, march 1, 2011, 12:00:00

I have an array item like this:



var array = USA.NY[2];
// gives Albany

{USA : {
NY : [New York City, Long Island, Albany]
}}


I want to find the state from just having the array. How do I do this? Thanks.



function findParent(array) {
// do something
// return NY
}

More From » arrays

 Answers
7

In Javascript, array elements have no reference to the array(s) containing them.



To achieve this, you will have to have a reference to the 'root' array, which will depend on your data model.

Assuming USA is accessible, and contains only arrays, you could do this:



function findParent(item) {
var member, i, array;
for (member in USA) {
if (USA.hasOwnProperty(member) && typeof USA[member] === 'object' && USA[member] instanceof Array) {
array = USA[member];
for(i = 0; i < array.length; i += 1) {
if (array[i] === item) {
return array;
}
}
}
}
}


Note that I’ve renamed the array parameter to item since you’re passing along a value (and array item), and you expect the array to be returned.

If you want to know the name of the array, you should return member instead.


[#93517] Monday, February 28, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eddiejoshb

Total Points: 659
Total Questions: 105
Total Answers: 100

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;