Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an arrays of array surrounded by quotes into string array

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,

  1. formattedArray1 = array1.replace(/","/g, " - ").reduce((a, b) => a.concat(b), [])

this gives me an error:

array2.reduce is not a function

  1. formattedArray2 = [].concat.apply([], array1.replace(/","/g, " - ")); and this gives me the error

CreateListFromArrayLike called on non-object

To fix this any thought would be highly appreciated!

like image 852
Sajith Wijerathne Avatar asked Dec 11 '25 21:12

Sajith Wijerathne


2 Answers

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

benchmark results

like image 138
Phil Avatar answered Dec 13 '25 09:12

Phil


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']
like image 34
Shri Hari Avatar answered Dec 13 '25 09:12

Shri Hari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!