Home > Blockchain >  Mixed Array of String and Number
Mixed Array of String and Number

Time:04-27

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);

CodePudding user response:

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);

CodePudding user response:

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);

CodePudding user response:

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.

  • Related