0

I am trying to split (in Vanilla JS) a string into a single or multiple arrays after each \n character.

For example :

let string = '1 2 3 4\n5 6 7 8\n9 8 7 6';

should return :

let combinedArrays = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 8, 7, 6]];

by splitting the let string after every \n character and deleting all the space characters.

Thanks for your help.

1
  • Using split js function Commented Jun 3, 2020 at 20:01

1 Answer 1

2
let combinedArrays = string.split('\n').map(el => el.split(' '))

let string = '1 2 3 4\n5 6 7 8\n9 8 7 6';
console.log(string.split('\n').map(el => el.split(' ')))

Please read more about split() method here: https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/String/split

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

2 Comments

Thanks. How the element el could be a Number(el) ?
Almost! You should use one more map operator. string.split('\n').map(el => el.split(' ').map(n => Number(n))) Please mark my answer liker correct)

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.