I have date duration values in following format.
array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"], ...]';
And need to convert it as follows,
array2 = [ '2022-01-18 - 2022-01-21', '2022-02-15 - 2022-02-17', ... ]
For the work done I have followed two ways,
formattedArray1 = array1.replace(/","/g, " - ").reduce((a, b) => a.concat(b), [])this gives me an error:
array2.reduce is not a function
formattedArray2 = [].concat.apply([], array1.replace(/","/g, " - "));
and this gives me the errorCreateListFromArrayLike called on non-object
To fix this any thought would be highly appreciated!
What you've got there is an array serialised to JSON.
You can parse it to an array then map it to the value you want
const array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';
const arr = JSON.parse(array1);
const array2 = arr.map(([from, to]) => `${from} - ${to}`);
console.log(array2);
If you're curious (like I was) about the performance of the template literal vs Array.prototype.join(), the results from https://jsbench.me are below...
Template literal
2678.21 ops/s ± 0.85%
Fastest
Array.prototype.join()
1150.62 ops/s ± 0.51%
57.04 % slower

array1 is stored as String, so you need to convert it to Array to use reduce or other array methods.
array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';
arr = JSON.parse(array1)
formattedArray1 = arr.map((e) => e.join(" - "))
// ['2022-01-18 - 2022-01-21', '2022-02-15 - 2022-02-17']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With