0

I am trying the following addition -

arr = ["12","15"];
let sum = arr[0] + 5;
console.log(sum)

It returns me 125 instead of 17. ( because 12 is a string ) I tried to convert this array into an array of numbers by using var string = JSON.stringify(arr).replace (/"/g,''); and then performing the addition but string[0] returns ' [ ' , for the obvious reason.

Is there a direct way to perform this addition?

kewlashu
  • 1,099
  • 10
  • 18
Itika Bandta
  • 163
  • 1
  • 2
  • 12
  • you could cast it to number using `Number()` constructor `let sum = Number(arr[0]) + 5;` – hgb123 Sep 11 '20 at 08:21
  • Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – CBroe Sep 11 '20 at 10:24

2 Answers2

0

Here you go:

arr = ["12","15"];
let sum = parseInt(arr[0]) + 5;
console.log(sum)

When any side of the + operation is a string then + operator does string concatenation in javascript

kewlashu
  • 1,099
  • 10
  • 18
0

The easiest way to convert an array of strings to an array of numbers, is with .map(Number):

let arr = ["12","15"].map(Number);

console.log(arr);
trincot
  • 317,000
  • 35
  • 244
  • 286