0

I have an array and want to split two data that contain in one array element.

Here is the code :

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] contain two data : 2 Florida 6 14 and 3 Texas 5 12. I need to split array[1] to two different arrays with each data.

Result i expect :

[
  "1",
  "Boston",
  "4",
  "11"
]
[
  "2",
  "Florida",
  "6",
  "14"
]
[
  "3",
  "Texas",
  "5",
  "12"
]
[
  "4",
  "California",
  "7",
  "13"
]

Anyone can please help me to solve that?

2 Answers 2

3

First split for each line break and then for each whitespace

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(" ")));

As kemicofa explained not all browsers support Array#flatMap. The recommended alternative for flatMap is a combination of Array#reduce and 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(" ")));

Sign up to request clarification or add additional context in comments.

Comments

1

Array#flatMap is not cross-compatible on IE or Edge. Here is an alternative with Array#join and 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.