'How to get max number from Array<String> in TS orJS
I'd like to create like this function in JS or TS but I couldn't.
Please teach me ...!
It is better if its function is made by functional-programming.
・Input type:Array(String)
・Output type:string or undefined
ex
| Input | Result |
|---|---|
["","0","3"] |
"3" |
["","",""] |
undefined |
["0","0","0"] |
"0" |
["1","3","2"] |
"3" |
Solution 1:[1]
- Filter out all non-number elements from array.
- Convert all string-number to Number type.
- Use
Math.maxto get the largest value from array.
function getMaxValue(input) {
if (input.length) {
return Math.max.apply(null, input);
}
}
function sanitize(input) {
return input.filter(i => {
if (i === "" || i === null) {
return false;
}
return !isNaN(i);
}).map(i => Number(i));
}
let input1 = ["", "", "0"];
let input2 = [1, 3, 5];
let input3 = ["1", "", "5"];
let input4 = ["", "", ""];
let input5 = [undefined, null, "", "", "", "10"];
console.log(getMaxValue(sanitize(input1)));
console.log(getMaxValue(sanitize(input2)));
console.log(getMaxValue(sanitize(input3)));
console.log(getMaxValue(sanitize(input4)));
console.log(getMaxValue(sanitize(input5)));
Solution 2:[2]
You can try this.
const findMaximuminArray = (arr) => {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
if(max === "") return undefined;
return max;
}
Solution 3:[3]
You are using strings in your example, such as "1", but all of them contain digits actually, so I'm not sure what you're really trying to do.
However, here's a function that generates the results you want using lodash/fp:
_.compose(x => x ? x : undefined, _.max)
Whatever array argument you pass to it, it will get the maximum value and then convert it to undefined if it is falsy, as is the case for the empty string.
Here's the results generated for your input:
const fun = _.compose(x => x ? x : undefined, _.max);
const input = [["","0","3"],["","",""],["0","0","0"],["1","3","2"]]
_.forEach(x => console.log(fun(x)), input);
<script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)"></script>
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 | Rayon |
| Solution 2 | Praveen Kumar Yadav |
| Solution 3 | Enlico |
