Reputation: 45
I am working on a coding challenge and the way the array is being input is: [ '10 2 5', '12 4 4', '6 2 2' ]
I want to make those numbers each their own, but because they are grouped weirdly like that in '', it is only taking the first value after each comma. Do you have any recommendations on how to break it out like [10, 2, 5], [12, 4, 4], [6, 2, 2] ?
This is what I've already tried:
function maximumContainers(scenarios) {
let newArr = []
for(let i = 0; i < scenarios.length; i++) {
newArr.push(parseInt(scenarios[i]))
console.log(newArr)
}
}
and the output I got was: [10, 12, 6]
So it's only taking the first string number after each quote.
Upvotes: 0
Views: 47
Reputation: 4783
Just loop through the original array and split each value based on the space char and assign it to the new array :
const arr = ["10 2 5", "12 4 4", "6 2 2"],
newArr = arr.map(el => el.split(" ").map(el => +el));
/** the "+" in "el => +el" casts the string to an integer **/
console.log(newArr);
Learn more about
split
function.Learn more about
map
function.
Upvotes: 2