David Addoteye
David Addoteye

Reputation: 1641

Return / Get x Number of Items From an Array in Typescript/Javascript

I have an array with over 200 items from a .json file.

I want to know how I can return lets say the first 10 items or 20 items starting from the 7th index/item.

Example

OriginalArray = [{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}, {i}, {j}, {k}, {l}]

How do I get newArray = [{a}, {b}, {c}, {d}] or newArray = [{e}, {f}, {g}, {h}]

from the originalArray in typeScript or Javascript.

Thank you

Upvotes: 0

Views: 1542

Answers (3)

Interface
Interface

Reputation: 342

In your case:

var newArray = OriginalArray.slice(7, 7+20);

Upvotes: 1

mplungjan
mplungjan

Reputation: 178079

You need slice

const offset = 7;
console.log(
  ["{a}", "{b}", "{c}", "{d}", "{e}", "{f}", "{g}", "{h}", "{i}", "{j}", "{k}", "{l}"]
  .slice(offset,offset+4)
)

Upvotes: 1

gabriel.hayes
gabriel.hayes

Reputation: 2313

Try this:

newArrayA = OriginalArray.slice(0, Math.round(OriginalArray.length/2)) // first half
newArrayB = OriginalArray.slice(Math.round(OriginalArray.length/2)) // second half

Upvotes: 2

Related Questions