sommersesongen
sommersesongen

Reputation: 11

TypeScript - Get max value from a mixed array

I have an array of arrays and I would like to find the max value of the first elements in those arrays.

Example:

[ [ 300, 600 ], [ 160, 600 ], [ 120, 600 ] ]

This example should return 300 because it is the max value of 300, 160 and 120.

This is an easy task and can be solved like this:

let first = array.map(item => item[0]);
let max = Math.max(...first); // max == 300

The problem is that I work with TypeScript and this array potentially can have a fixed string in it like so:

[ 'something' ]

No matter what I try to do I get errors from different places. For example I try something like this:

array.filter(item => item != "something").map(item => item[0]);

I cannot change the original array. So how can I overcome this issue with TypeScript? Thanks for help.

Upvotes: 0

Views: 8286

Answers (4)

Prathap Reddy
Prathap Reddy

Reputation: 1739

Filter out only number values using isNaN after getting the list of first values from array inside the array

let first = array.map(item => item[0]).filter(val => !isNaN(val));

Then perform Math.max on the resulted array

let max = Math.max(...first); 

Upvotes: 2

macborowy
macborowy

Reputation: 1544

Try to filter array like this:

const array = [[300, 600], [160, 600], [120, 600], ["something"]];
let first = array
  .filter(item => !isNaN(Number(item[0])))
  .map(item => Number(item[0]));
let max = Math.max(...first);

console.log('Max', max);

When item[0] is not a number Number() returns NaN that is filtered out by checking !isNaN(Number(item[0])).

Upvotes: 0

Çağatay Sel
Çağatay Sel

Reputation: 810

You can change map function to map strings to integer min so that they do not affect your max calculations

let first = array.map(item => typeof(item[0]) !== "string" ? item[0] : Number.MIN_VALUE);
let max = Math.max(...first); // max == 300

Upvotes: 0

Kavian Rabbani
Kavian Rabbani

Reputation: 984

The point is that filter and map methods are immutable and do not change the original array.
There should be no problem with this snippet:

const max = Math.max(...(array
  .filter(item => item !== "sth")
  .map(item => item[0])
));

Upvotes: 0

Related Questions