简体   繁体   中英

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

Try this:

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

You need slice

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

In your case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM