简体   繁体   中英

Javascript return number less than 100 given an array with numbers and strings

Given below, how do I write a function that will return a number less than 100?

const myArray = ['hello', 3, true, 18, 10,, 99 'ten', false]

const isLessThan100 = (array) => {
  // how to do this? Solution enter here
}

I think it involves the filter method, but im not sure how to filter both a number less than 100, and is not a string.

Thanks in advance!

you can check if it is a number first like this

const myArray = ['hello', 3, true, 18, 10, 99, 'ten', false];

const isLessThan100 = myArray.filter(item => {
  return (typeof item === "number") && item < 100;
});

The typeof operator returns a string indicating the type of the unevaluated operand.

You can first check whether the typeof the item is number or not, then check if it is less than 100 .

You can reduce the code to a single line by removing the curly braces.

Try Array.prototype.filter() like the following way:

 const myArray = ['hello', 3, true, 18, 10,, 99, 'ten', false] const isLessThan100 = (array) => array.filter(num => typeof(num) === "number" && num < 100); console.log(isLessThan100(myArray)) 
 const isLessThan100 = (array) 

Here's a short-ish one using filter :

 const myArray = ['hello', 3, true, 18, 10, 99, 101, 'ten', false]; const isLessThan100 = a => a.filter(e => +e === e && e < 100); console.log(isLessThan100(myArray)); 

For getting only a single value, you could reduce the array.

 const array = ['hello', 3, true, 18, 10,, 99, 'ten', false], isLessThan100 = array => array.reduce((r, v) => typeof v === 'number' && v < 100 && (typeof r !== 'number' || v > r) ? v : r, undefined); console.log(isLessThan100(array)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM