我有一个数组,想要拆分一个数组元素中包含的两个数据。
这是代码:
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"
]
有人可以帮我解决这个问题吗?
最佳答案
首先针对每个换行符进行拆分,然后针对每个空格进行拆分
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(" ")));
关于javascript - 如何在一个数组元素中拆分两个数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53459139/