Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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']
about 4 years ago · Juan Pablo Isaza Report

0

  1. You are calling reduce on type string( 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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!