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

2
  • Did you try Array.prototype.slice()? Commented Aug 9, 2017 at 15:58
  • top = arr.slice(0, 3); Commented Aug 9, 2017 at 15:58

3 Answers 3

4

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

return this.users.sort(this.triDec).slice(0, 3);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-1

Fill out the deletecount for Splice:

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

check MDN

1 Comment

Why the downvote? For using splice instead of slice? OP didn't mention the original array should be maintained.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.