Converting Array stored as a String to a List object in JavaString

Issue

I have the following list:

nested_list = [
  ["[63]"],
  ["[61]"],
  ["[7]"],
  ["[63]"],
  ["[80, 18]"],
  ["[80, 43, 18, 20]"]
]

Which is a mess I know, but this is the data that I have to deal with at the moment and
I need it to be like this:

[63, 61, 7, 63, 80, 18, 80, 43, 18, 20]

So basically converting it into a list of numbers. Is this doable using as minimum loops as possible?

I have used flat() nested_list .flat(2) and ended up with the following result:

[ '[63]', '[61]', '[7]', '[63]', '[80, 18]', '[80, 43, 18, 20]' ]

Also tried reduce + concat following this but since it is a string, it is not working and I’m not sure where to go from here.

Solution

.flatMap() + JSON.parse() can do this quite easily

const nested_list = [
  ["[63]"],
  ["[61]"],
  ["[7]"],
  ["[63]"],
  ["[80, 18]"],
  ["[80, 43, 18, 20]"]
];

const result = nested_list.flatMap(JSON.parse);

console.log(result)

Answered By – Andreas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published