Reputation: 13389
I have a string like:
const coordonate = 'a5';
I want to split the letter that will be transformed latter into a number which represents the column and the <5> which represents the row.
For this I do something like this:
[columnLetter, row] = coordinate.split('');
column = getColumnByLetter(columnLetter); // Returns a number.
....
result = doSomethingWithNumbers(column, row); // The problem is row is a String.
I could do:
result = doSomethingWithNumbers(column, Number(row));
But I'm wondering if there is a way to retrieve directly row as number... Something like:
[columnLetter, Number(row)] = coordinate.split('');
Upvotes: 4
Views: 848
Reputation: 386560
You could check the value with isNaN
and take numbers or strings for NaN
values.
var string = 'a5',
[row, col] = string.split('').map(v => isNaN(v) ? v : +v);
console.log(typeof row, row);
console.log(typeof col, col);
Upvotes: 2
Reputation: 138267
If your aim is to do that in one line:
doSomethingWithNumbers(coordinate[0], Number(coordinate[1]))
Upvotes: 0
Reputation: 1873
You could use map function.
const coordinate = 'a5';
[columnLetter,row] = coordinate.split('').map((item) => typeof item == 'number' ? Number(item) : item);
console.log(columnLetter, row)
Upvotes: 0
Reputation: 50684
You could use Array.from
to make an array from your coordinates string, where each character is coerced to a number or left as a string:
const coordinate = 'a5';
[columnLetter, row] = Array.from(coordinate, c => +c || c); // [str: 'a', num: 5]
console.log(typeof columnLetter, typeof row);
Upvotes: 0
Reputation: 10398
Just reassign the variable:
const coord = 'A5'
let [ col, row ] = coord.split('')
row = Number(row)
console.log(typeof col, col);
console.log(typeof row, row);
Or map the values:
const coord = 'A5'
const [col, row] = coord.split('').map(i => +i || i)
console.log(typeof col, col);
console.log(typeof row, row);
Upvotes: 1