简体   繁体   中英

Add elements to an array from specified position in typescript

I am adding elements to array arr1 using map function. Is there any way to specify the index of starting position in typescript

eg If I want to add elements from 3rd index position of the array. first two index should hold 0. how can I do that?

 let years = [0,1,2,3,4]; data = { var1: 100000, arr2: years.map(_ => 1000) }; console.log(data.arr2); 

I want to add 0 from starting of the array. If I specify position as 3 then first 2 element should be zero

You can use array#map and for all index value lower than your desired index place 0 other get the value from your array.

 let years = [0,1,2,3,4], index = 2, result = years.map((v,i) => i < index ? 0 : v); console.log(result); 

I'm not sure if I understood what you want :

 let years = [0,1,2,3,4]; data = { var1: 100000, arr2: modifyArray(3, 100000) }; console.log(data.arr2); function modifyArray(position = 0, value) { const newArray = []; for (let i = 0; i < position - 1; i++) { newArray.push(0); } return [...newArray, ...years.slice(0, position ), value, ...years.slice(position)]; } 

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