I have array of 10 elements, I am mapping to extract array data . I want to stop array executing when compile reached to array index 5 . I know it possible with for loop but I need it in map function. Please help me
Asked
Active
Viewed 36 times
0
-
`map` can't do that but you can achieve that with `reduce` or `filter` – user1984 Aug 21 '19 at 19:14
-
@Alireza can you please make a simple array and apply this function – Jonas Aug 21 '19 at 19:22
-
You mean `reduce` and `filter`? – user1984 Aug 21 '19 at 19:22
-
Why not just map the whole array till the 5th index with a combination of `slice` and `map`? – Rohit Kashyap Aug 21 '19 at 19:26
-
Actually you can stop execution using `[1,2,3,4,5,6,7,8,9,10].map((x,i) => { if(i>=5) throw 0; console.log(x**2) })` - however throw exception will slow down your code and they are not designed for break loops in normal situations – Kamil Kiełczewski Aug 21 '19 at 19:30
-
@Alireza please try best one , actually I want to solve my problem – Jonas Aug 21 '19 at 19:33
-
What ever requirement you have to accomplish this for is nonsense – SpeedOfRound Aug 21 '19 at 19:34
-
`[1,2,3,4,5,6,7].slice(5)` or `[1,2,3,4,5,6,7].filter((el,i) => i <5)` slice is the one for this job. If you need to transform only the first 5 elements chain `slice` with map. – user1984 Aug 21 '19 at 19:37