Search code examples
jqueryobjectindexofhowler.js

Object Math.max and indexof to get the index


I have the following object:

var thisArray = {
   user1: sounduser1,
   user2: sounduser2
};

sounduser1 and sounduser2 are audiofiles played through howler.js (great script!)

Using ._duration you'll get a number - the length of the audio.

I wanted to get the longest audio, which I did get through:

var audiogetlength = Object.keys( thisArray ).map(function ( key ) { 
                        return thisArray[key]._duration;
                     });
var longest = Math.max.apply( null, audiogetlength );

What I would like is the original [key] (or index?) of the longest audiofile: var longest

So I tried indexOf

var thisone = longest.indexOf(longest ));

But it doesn't seem to be logical… and it doesn't work…

Am I on the right track?


Solution

  • What's wrong with a good old for loop?

    var keys = Object.keys( thisArray ),
        maxDuration = 0,
        maxKey;
    for( var i=keys.length; i--; ) {
      if( thisArray[ keys[i] ]._duration > maxDuration ) {
        maxKey = keys[i];
        maxDuration = thisArray[ keys[i] ]._duration;
      }
    }
    
    // maximum (longeste) length in maxDuration
    // respective key in maxKey