I am developing a project with angular, and I have come across a problem while joining an array to a string and splitting it with ‘,’
Here’s an example
let numbers = [2019, 2020, 2021, 2022, 2023] numbers.toString().split(',').join(', ')
Outputs as
"2019, 2020, 2021, 2022, 2023"
Here’s my problem I want an & symbol at the 2nd last of last number being parsed
Output something like
"2019, 2020, 2021, 2022 & 2023"
Is there any elegant way to do with while doing split().join()
I know of brute force ways (there are many), but any optimal way of doing this?
Thanks in advance.
I tried doing pushing at index(-2) from the end, not an elegant way tbh, the numbers array is very dynamic.
splitting the string and then looping over it and at the end when we encounter the last space, replacing it with &, but this will require creating a copy of whole string.
>Solution :
We can use Array.slice() and Array.at() to do it
let numbers = [2019, 2020, 2021, 2022, 2023]
let result = numbers.slice(0,-1).toString().split(',').join(', ')+ ' & ' + numbers.at(-1)
console.log(result)