why my data is missing in splition function?

Viewed 73

i have array = ["cstomer~12.3,74.3~249" ," bhai~31.6,74.38~519"]

and i am spliting it by this code

array = ["cstomer~12.3,74.3~249" ," bhai~31.6,74.38~519"];

var input = [...array.reduce((items, item) => (item.length && (items = [...items, item.split("~")]), items), [])];
let locations = input.reduce((p, c, i) => {
    p[i] = [c[0], ...(c[1].split(",").map(y => +y))];
    return p;
  },[]);
  
console.log(locations);

resutl is 
[(Array), (Array)] = [["cstomer", 12.3,74.3], 
                       ["bhai", 12.3,74.3] ]

but it is missing 249 and 512

required result is

[["cstomer", 12.3,74.3, 249], 
 ["bhai", 12.3,74.3, 512] ]
3 Answers

You could split and split the nested parts, get a flat array and convert all values to numbers, if index is not zero.

const
    array = ["cstomer~12.3,74.3~249", "bhai~31.6,74.38~519"],
    result = array.map(s => s
        .split(',')
        .flatMap(s => s.split('~'))
        .map((v, i) => i ? +v : v)
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can simplify your code by splitting each element on , and then using reduce to split each of those values by ~ and pushing them to a result array:

const array = [
  "cstomer~12.3,74.3~249",
  "bhai~31.6,74.38~519"
];

const result = array
  .map(s => s
    .split(',')
    .reduce((c, v) => c.concat(v.split('~')), [])
    .map((v, i) => i ? +v : v)
  );

console.log(result);

You should split with both , and ~.

Change:

item.split("~")]

To:

item.split(/[~,]/)])

You can simply use map() and split() like the following way:

var array = ["cstomer~12.3,74.3~249" ," bhai~31.6,74.38~519"];
var locations = array.map(item => (item.split(/[~,]/).map(i => isNaN(i)? i.trim() : +i)));
console.log(locations);

Related