'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);
Solution 1:[1]
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.
Solution 2:[2]
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);
Solution 3:[3]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AVLESSI Matchoudi |
| Solution 2 | Jakub Kotrs |
| Solution 3 | mgm793 |
