0

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

Luuuud
  • 4,206
  • 2
  • 25
  • 34
moonshine
  • 799
  • 2
  • 11
  • 24

3 Answers3

3

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

return this.users.sort(this.triDec).slice(0, 3);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Don't you want to use a const value for diffSplice like

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

try running

let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));

refer to Array Silce

marvel308
  • 10,288
  • 1
  • 21
  • 32
-1

Fill out the deletecount for Splice:

var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);

check MDN

Luuuud
  • 4,206
  • 2
  • 25
  • 34
  • Why the downvote? For using `splice` instead of `slice`? OP didn't mention the original array should be maintained. – Luuuud Aug 09 '17 at 16:01