user14477068
user14477068

Reputation:

how to split array into miltiple array?

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)
     ];

Upvotes: 0

Views: 42

Answers (1)

renich
renich

Reputation: 146

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);

Upvotes: 1

Related Questions