admin管理员组

文章数量:1426118

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!

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!

Share Improve this question edited Aug 4, 2018 at 5:30 asked Aug 4, 2018 at 4:12 user7426291user7426291 2
  • Might be you have convert that each item to an integer and then pare? – Prashant Pimpale Commented Aug 4, 2018 at 4:14
  • please add the wanted result as well. is it a single value or more than one values? – Nina Scholz Commented Aug 4, 2018 at 6:57
Add a ment  | 

4 Answers 4

Reset to default 4

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

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

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)

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

本文标签: Javascript return number less than 100 given an array with numbers and stringsStack Overflow