Reputation: 139
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!
Upvotes: 3
Views: 264
Reputation: 7204
Another Alternative
The transform could also be done at the same time the json is parsed by providing a reviver function that evaluates each key-value. if the value is a child array then join the elements.
let json = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';
let data = JSON.parse(json, (k,v) => k && v.push ? v.join(" - ") : v );
console.log(data);
Upvotes: 2
Reputation: 1568
array1.replace(/","/g, " - ")
will return a string) , reduce works only with Array.prototype
that's why you are getting reduce
is not a function.array2.reduce is not a function error.
You need to parse the array before doing reduce.
const array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';
const parsedArr = JSON.parse(array1);
const result = parsedArr.map(date => date.join(" - ") )
console.log(result)
Upvotes: 2
Reputation: 164830
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
Upvotes: 4
Reputation: 4904
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']
Upvotes: 2