Skip to main content
Inspiring
January 24, 2018
Question

how do I find an object's index in an array

  • January 24, 2018
  • 1 reply
  • 505 views

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...

This topic has been closed for replies.

1 reply

kglad
Community Expert
Community Expert
January 25, 2018
  • 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 
Inspiring
January 25, 2018

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)

kglad
Community Expert
Community Expert
January 25, 2018

index_min is that index number.