我有一个数组,想拆分一个数组元素中包含的两个数据。
这是代码:
const array = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];
array.map(x => {
return (
console.log(x.split(" "))
)
});
array[1]
包含两个数据:2 Florida 6 14
和3 Texas 5 12
。我需要将array[1]
分成两个不同的数组,每个数据。
我期望的结果:
[
"1",
"Boston",
"4",
"11"
]
[
"2",
"Florida",
"6",
"14"
]
[
"3",
"Texas",
"5",
"12"
]
[
"4",
"California",
"7",
"13"
]
任何人都可以帮助我解决这个问题吗?
答案 0 :(得分:3)
为每个换行符先分割,然后为每个空格
const array = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];
console.log(array.flatMap(x => x.split("\n")).map(x => x.split(" ")));
正如kemicofa所述,并非所有浏览器都支持Array#flatMap。推荐的FlatMap alternative是Array#reduce和Array#concat的组合:
const array = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];
console.log(array.reduce((acc, x) => acc.concat(x.split("\n")), []).map(x => x.split(" ")));
答案 1 :(得分:1)
Array#flatMap在IE或Edge上不兼容。这是Array#join和String#split
的替代方法
const data = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];
const res = data.join("\n").split("\n").map(item=>item.split(" "));
console.log(res);