I have an array containing two strings: '1' and '5' for example. I want to save those two strings into parameters, but already as integer numbers. Currently, the code looks like this:
const data = ['1', '5'];
const [min_str, max_str] = data;
const min = parseInt(min_str, 10);
const max = parseInt(max_str, 10);
console.log(typeof min_str, typeof max_str, typeof min, typeof max)
Is there a way to reduce this code to one line, such that parseInt has already been applied to min_str and max_str?
You could map the data before destructing
const [min, max] = data.map(d => parseInt(d, 10));
Maybe you can use map()
const [min_str, max_str] = data.map(x => parseInt(x, 10));
If the strings are only numbers inside strings. You can also use Number
const [min_str, max_str] = data.map(Number);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With