0

Let's say I'm working with an array that has a bunch of items, always over 20, but never the same amount. I want to trim that array to just 10 items. The answer here doesn't take into account varying sized arrays.

What's a good way to do this?

Community
  • 1
  • 1
dallen
  • 2,621
  • 7
  • 37
  • 47
  • 1
    Until you give more specifics as to any criterion for what to keep, or show some code, I'm going with: `array.slice(0, 10)`. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fslice – Scott Mermelstein Aug 20 '13 at 16:00

2 Answers2

4

You can slice an array with Array.slice() :

new_array = old_array.slice(0,10);

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

This trims the array in place:

arr.length = 10;
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143