i have an array output
["AA janral store shahid bhai Islam pura,31.592887,74.4292156,1~", "Almakkah store shahid bhai gunj bazar,31.5645088,74.3838828,1~", "hamad hassan Nafees backery,31.595234,74.3565654,1~"]
but required output is in javascript
[Array(), Array(), Array()]
example
var ar = [
['AA janral store shahid bhai Islam pura',31.592887,74.4292156,1],//(array)
['Almakkah store shahid bhai gunj bazar',31.5645088,74.3838828,1],//(array)
['hamad hassan Nafees backery',31.595234,74.3565654,1]//(array)
];
asked Oct 22, 2020 at 8:55
user14477068
-
Does this answer your question? How can I convert a comma-separated string to an array?Krzysztof Krzeszewski– Krzysztof Krzeszewski2020年10月22日 08:57:41 +00:00Commented Oct 22, 2020 at 8:57
-
no this is different oneuser14477068– user144770682020年10月22日 08:59:23 +00:00Commented Oct 22, 2020 at 8:59
1 Answer 1
If commas are always separators, so:
const arr = ["AA janral store shahid bhai Islam pura,31.592887,74.4292156,1~", "Almakkah store shahid bhai gunj bazar,31.5645088,74.3838828,1~", "hamad hassan Nafees backery,31.595234,74.3565654,1~"];
const res = [...arr.map(item => item.split(","))];
console.log(res);
The same with filtering blank strings:
const arr = ["AA janral store shahid bhai Islam pura,31.592887,74.4292156,1~", "", "Almakkah store shahid bhai gunj bazar,31.5645088,74.3838828,1~", "hamad hassan Nafees backery,31.595234,74.3565654,1~"];
const res = [...arr.reduce((items, item) => (item.length && (items = [...items, item.split(",")]), items), [])];
console.log(res);
With different variants of incoming data:
const arr = ["AA janral store shahid bhai Islam pura,31.592887,74.4292156, ", "", " ", ",,,,,", "Almakkah store shahid bhai gunj bazar,31.5645088,74.3838828,1~", "hamad hassan Nafees backery,31.595234,74.3565654,1~"];
const res = [...arr.reduce((items, item) => {
const splitted = item.split(",").filter(item => item.trim().length);
if (splitted.length) items.push(splitted);
return items;
}, [])];
console.log(res);
Sign up to request clarification or add additional context in comments.
5 Comments
renich
I added an example with an empty string.
renich
I also added the most complex example that I could think of.
legend bro but i want some more complexity like ["AA janral store shahid bhai Islam pura", 31.592887, 74.4292156, 1] means [ "string" , 1234,456 , 1] i am spliting value using '~' but in return it pass me string ["Almakkah store shahid bhai gunj bazar", "31.5645088,74.3838828,1", ""] but required is [ "string in cotation" , number without double cotation , 1]
lang-js