我有array = ["cstomer~12.3,74.3~249" ," bhai~31.6,74.38~519"]
我正在通过此代码拆分
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] ]
但它缺少249和512所需结果是
[["cstomer", 12.3,74.3, 249],
["bhai", 12.3,74.3, 512] ]
最佳答案
如果index不为零,则可以拆分和拆分嵌套部分,获得平面数组并将所有值转换为数字。
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; }