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
4 Answers
Reset to default 4you 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
版权声明:本文标题:Javascript return number less than 100 given an array with numbers and strings - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745412154a2657519.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论