0

I have a simple array of string but I am trying to convert it to array of decimal numbers like [5.22,8.22,rest of the numbers], but it is returning only array of whole numbers.

I am doing some rookie mistake which I am not able to notice

let k = ["5:17", "8:22", "3:34", "5:23",
         "7:12", "7:24", "6:46", "4:45",
         "4:40", "7:58", "11:51", "9:13",
         "5:50", "5:52", "5:49", "8:57",
         "11:29", "3:07", "5:59", "3:31"];

let arrOfNum = k.reduce(function(acc, crr) {
  acc.push(parseFloat(crr))
  return acc;
}, [])

console.log(arrOfNum)

2 Answers 2

4

Change acc.push(parseFloat(crr)) to acc.push(parseFloat(crr.replace(":",".")))

JavaScript doesn't recognize colons as periods

Sign up to request clarification or add additional context in comments.

Comments

1

A float number doesn't follow this format integer:decimal,

it follows `integer.decimal`
                   ^
                   |
                   +--- the dot is the decimal separator in JS.

On the other hand, you don't need reduce for doing that, use the function map instead.

Likewise, I recommend you to use the object Number. If you want, you can read a little about it here

let k = ["5:17", "8:22", "3:34", "5:23","7:12", "7:24", "6:46", "4:45","4:40", "7:58", "11:51", "9:13","5:50", "5:52", "5:49", "8:57","11:29", "3:07", "5:59", "3:31"],
    arrOfNum = k.map((crr) => Number(crr.replace(':', '.')));

console.log(arrOfNum);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.