I have a text whose type is string and not array, as shown below:
'[123,456],[789],[10]'
- I want the count of number of arrays in this string(in this case it will be 3)
- I want the number of elements in each array.
I can't use split with commas because there are commas between the numbers in that "array".
And I need to determine the length of those 3 arrays, how do I do that?
Desired result:
array: 3
length: 2,1,1
CodePudding user response:
You could add an array in the string so you end up with an actual json array.
Then you can parse the json and count them.
let value = '[' '[123,456],[789],[10]' ']';
let json = JSON.parse(value);
json.forEach((item, i) => {
console.log('length: ' item.length)
});
console.log(json.length ' items')