Search code examples
javascriptarrayssortingsplice

how can i have the first 3 elements of an array of variable length in Javascript


i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.

here's what i've done :

var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)

my "solution" work only for an array of 4 element ( -1 )

Is there a better way to use the splice method ?

Thanks for your help


Solution

  • You could use Array#slice for the first three items.

    return this.users.sort(this.triDec).slice(0, 3);