Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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"
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!