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

Given below, how do I write a function that will return a number less than 100?const myArray = ['h

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745412154a4626583.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信