Home > Mobile >  How to get max number from Array<String> in TS orJS
How to get max number from Array<String> in TS orJS

Time:03-26

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"

CodePudding user response:

  • Filter out all non-number elements from array.
  • Convert all string-number to Number type.
  • Use Math.max to 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)));

CodePudding user response:

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

CodePudding user response:

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>

  • Related