Rushabh Gandhi
Rushabh Gandhi

Reputation: 33

Mixed Array of String and Number

I have an array that consists of a string and number ("2",3,4). I want to multiply the same and get an output of 24.

I tried this method but getting an error of "Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'."

var stringArray = ["2",3,4];
var numberArray = [];

length = stringArray.length;

for (var i = 0; i < length; i++)
  numberArray.push(parseInt(stringArray[i]));
console.log(numberArray);

Upvotes: 2

Views: 1635

Answers (3)

AVLESSI Matchoudi
AVLESSI Matchoudi

Reputation: 56

Since you want to multiply.
var stringArray = ["2",3,4]; let res = stringArray.reduce((a,b) => a*b); the Reduce method will do conversion for you.

Upvotes: 1

Jakub Kotrs
Jakub Kotrs

Reputation: 6229

parseInt expects and argument of type string. However, since your array also contains numbers, you are calling it with a number, eg. parseInt(3), which is why you are getting the error.

A possible solution is to check manually and give a hint

var stringArray = ["2",3,4];
var numberArray = [];

length = stringArray.length;

for (var i = 0; i < length; i++) {
  let value;
  if (typeof stringArray[i] === 'string') {
     value = parseInt(stringArray[i] as string)
  } else {
     value = stringArray[i]
  }
  numberArray.push(value);
}
console.log(numberArray);

Upvotes: 2

mgm793
mgm793

Reputation: 2066

You can do it using the + operator like this:

var stringArray = ["2", 3, 4];

let res = 1;
for (var i = 0; i < stringArray.length; i++) {
  res *= +stringArray[i];
}

console.log(res);

Upvotes: 1

Related Questions