how do I find an object's index in an array
Copy link to clipboard
Copied
Hi,
I've got this code that is looking for the closest number to 0 in my array :
var tideArray = new Array();
tideArray.push({tide:"haute", difference: "-14"});
tideArray.push({tide:"haute", difference: "3"});
tideArray.push({tide:"basse", difference: "-4"});
tideArray.push({tide:"basse", difference: "8"});
if (tideArray.length > 0)
{
var minItem: Object = tideArray[0];
for (var index:int = 1; index < tideArray.length; index++)
{
if (Math.abs(tideArray[index].difference) < Math.abs(minItem.difference))
{
minItem = tideArray[index];
}
}}
trace(minItem.difference) // OUTPUT is 3 in this case
Is there a way to find the index of minItem.difference in my tideArray ? (so, the result here should be index = 1 )
I've tried tideArray.indexOf(minItem.difference)
but the output is -1, so the index wasn't found...
Copy link to clipboard
Copied
- var tideArray = new Array();
- var index_min:int
- tideArray.push({tide:"haute", difference: "-14"});
- tideArray.push({tide:"haute", difference: "3"});
- tideArray.push({tide:"basse", difference: "-4"});
- tideArray.push({tide:"basse", difference: "8"});
- if (tideArray.length > 0)
- {
- var minItem: Object = tideArray[0];
- for (var index:int = 1; index < tideArray.length; index++)
- {
- if (Math.abs(tideArray[index].difference) < Math.abs(tideArray[index_min].difference))
- {
- index_min = index;
- }
- }
- }
- trace(tideArray[index_min].difference) // OUTPUT is 3 in this case
Copy link to clipboard
Copied
Hmm I must have explain badly what I wanted.
I'm looking for the index number and not the value of "difference" or "tide".
So, in the example, I'd like to output "1" (as it's the second object in the array that is selected)
Copy link to clipboard
Copied
index_min is that index number.

