我有一个数组,想要拆分一个数组元素中包含的两个数据。
这是代码:
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。推荐alternative对于 flatMap 来说,它是 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/