V. Sambor
V. Sambor

Reputation: 13389

Array destructuring to number type

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

Answers (5)

Nina Scholz
Nina Scholz

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

Jonas Wilms
Jonas Wilms

Reputation: 138267

If your aim is to do that in one line:

doSomethingWithNumbers(coordinate[0], Number(coordinate[1]))

Upvotes: 0

matvs
matvs

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

Nick Parsons
Nick Parsons

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

James Coyle
James Coyle

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

Related Questions