0

Javascript

I am a beginner, and I have a problem with 1 task;

let numbers='1.54,4.005,6,2.1,3.50';

I am trying to create an array where I will push these strings as numbers, to get array like this;

array=[1.54, 4.006, 6, 2, 1, 3.50]; I tried several methods; parseInt, numbers*1, Number(numbers). but it does not work. Please assist.

Katerina
  • 11
  • 2
  • 2
    `const array = numbers.split(',').map(n => Number(n))` should do it. (Or the shorter, but less obvious form of `.map(Number)` instead of `.map(n => Number(n))` - but this won't work with everything, it just "happens" to work with `Number` because it looks only at a single argument.) – CherryDT Jun 22 '22 at 20:04
  • Thanks :) Nope, it is not working, , Result: [ 1, NaN, NaN, NaN, 50 ] – Katerina Jun 22 '22 at 20:08
  • 1
    What do you mean? You can [see here](https://jsfiddle.net/qn65oxd2/) that it works. Please include the full code that's failing for you in your question, ideally as runnable snippet so we can see it live. – CherryDT Jun 22 '22 at 20:09
  • My bad, I incorrectly put "." instead of ",", thank you so much :)) It is working now <3 – Katerina Jun 22 '22 at 20:13

2 Answers2

1

You can split the string on commas to create an array, then use Array#map to convert each element. The unary plus operator, parseFloat, or the Number function can convert a string to a number.

let numbers='1.54,4.005,6,2.1,3.50';
let res = numbers.split(',').map(x => +x);
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Split the string into an array of strings, then use Number on each item with Array.map

numbers.split(',').map(Number);
asportnoy
  • 2,218
  • 2
  • 17
  • 31