admin管理员组文章数量:1287120
I've been trying for the past few hours to find out how to find numbers in array that are between 2 numbers and I don't know where to go. What do I need to do? 18 and 20 are just placeholder numbers, feel free to use any numbers you want.
function start() {
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var lower = 18;
var upper = 20;
if (need help here) {
alert('Yes');
} else {
alert('No');
}
document.getElementById('listOfvalues').innerHTML = ('There are ' + ___ + ' numbers that are between the two numbers);
document.getElementById('numberExist').innerHTML = numberExist;
}
I know I haven't provided much, but I will go crazy if I try to do this myself
I've been trying for the past few hours to find out how to find numbers in array that are between 2 numbers and I don't know where to go. What do I need to do? 18 and 20 are just placeholder numbers, feel free to use any numbers you want.
function start() {
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var lower = 18;
var upper = 20;
if (need help here) {
alert('Yes');
} else {
alert('No');
}
document.getElementById('listOfvalues').innerHTML = ('There are ' + ___ + ' numbers that are between the two numbers);
document.getElementById('numberExist').innerHTML = numberExist;
}
I know I haven't provided much, but I will go crazy if I try to do this myself
Share Improve this question edited Apr 16, 2017 at 11:58 Ghrafkly asked Apr 16, 2017 at 11:48 GhrafklyGhrafkly 1154 silver badges12 bronze badges 4- 1 please add the wanted result as well. – Nina Scholz Commented Apr 16, 2017 at 12:00
- The final output will say the number of values between those 2 values. So in my example where I used 18 and 20, the final result should be '6'. This would vary with different values as constraints – Ghrafkly Commented Apr 16, 2017 at 12:09
-
1
please highlight, how do you get
6
. – Nina Scholz Commented Apr 16, 2017 at 12:14 - Well, between 18 and 20, there is 18, 20, 18, 19, 18, 20. If, let's say the numbers were 20 and 30, 5 numbers fit the criteria, 23, 20, 21, 22, 20. Hope this helps – Ghrafkly Commented Apr 16, 2017 at 12:18
5 Answers
Reset to default 4var lower = 18;
var upper = 20;
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var between = array.filter(function(item) {
return (item > lower && item < upper);
});
var listOfvalues=[];
for(var i=0;i<array.length;i++){
if (array[i]>18 && array[i]<20) {
listOfvalues.push(array[i]);
}
}
document.getElementById('listOfvalues').innerHTML = 'There are ' + listOfvalues.length + ' numbers that are between the two numbers';
You could test, if the value is in the given range and count it.
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
lower = 18,
upper = 20,
result = array.reduce(function (r, a) {
return r + (a >= lower && a <= upper);
}, 0);
console.log(result);
ES6
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
lower = 18,
upper = 20,
result = array.reduce((r, a) => r + (a >= lower && a <= upper), 0);
console.log(result);
How does
Array#reduce
work in this case?You have an accumulator for the result, denoted as
r
and an actual value of the iteration, denoted asa
. The returned result is the sum of the former count and the ckeck, if the value is in the given range.r a return ment ------ ------ ------ -------- 0 18 1 in range 1 23 1 1 20 2 in range 2 17 2 2 21 2 2 18 3 in range 3 22 3 3 19 4 in range 4 18 5 in range 5 20 6 in range 6 result
Some thoughts, all in ES6 style.
You could use a callback for Array#reduce
with a closure over lower
and upper
, like
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
getCountInRange = (lower, upper) => (r, a) => r + (a >= lower && a <= upper);
console.log(array.reduce(getCountInRange(18, 20), 0));
or you could use a function which takes the array, lower
and upper
and returns the count.
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
getCountInRange = (array, lower, upper) => array.reduce((r, a) => r + (a >= lower && a <= upper), 0);
console.log(getCountInRange(array, 18, 20));
One approach is the following:
// a changed (hopefully meaningful) name for the function,
// lower: Number, the lower-boundary,
// upper: Number, the upper-boundary,
// haystack: Array, the array of values:
function numbersBetween(lower, upper, haystack) {
// if every value of the Array is, or can be coerced to,
// a Number then we continue to work with that Array:
if (haystack.every(value => Number(value))) {
// Here we use Array.prototype.filter() to filter the
// values of the Array according the function:
return haystack.filter(
// here we use an Arrow function, since we don't need
// to use a 'this'; here we retain the current value ('n')
// in the Array if that Number is greater than the
// lower-boundary and lower than the upper-boundary:
n => n > lower && n < upper
);
}
// otherwise, if not every value is, or can be coerced,
// to a Number we simply return an empty Array:
return [];
}
// this caches the element with the id of 'output':
let list = document.getElementById('output'),
// we create an <li> element:
li = document.createElement('li'),
// we create a document fragment:
fragment = document.createDocumentFragment(),
// and an empty uninitialised variable:
clone;
// we call the numbersBetween function, passing in the relevant
// boundaries and the Array:
numbersBetween(7, 20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15])
// because the function returns an Array (either an empty Array or
// an Array with values), we can chain the function using
// Array.prototype.forEach():
.forEach(
// here we use another Arrow function expression:
num => {
// clone the created <li> element and assign it
// the 'clone' variable:
clone = li.cloneNode();
// set the clone's textContent to be equal to
// the current Array-element of the Array over
// which we're iterating:
clone.textContent = num;
// and append that cloned-element to the
// document.fragment:
fragment.appendChild(clone);
});
// this could be used in the last iteration of the
// Array.prototype.forEach() method, but because it
// generates no errors (an empty document fragment
// can be appended to an element without consequence),
// we perform this step here, appending the document
// fragment to the cached 'list' element which appends
// the nodes contained within the document fragment to
// the specified parent-node (list):
list.appendChild(fragment);
function numbersBetween(lower, upper, haystack) {
if (haystack.every(value => Number(value))) {
return haystack.filter(
n => n > lower && n < upper
);
}
return [];
}
let list = document.getElementById('output'),
li = document.createElement('li'),
fragment = document.createDocumentFragment(),
clone;
numbersBetween(7, 20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15]).forEach(
num => {
clone = li.cloneNode();
clone.textContent = num;
fragment.appendChild(clone);
});
list.appendChild(fragment);
#output::before {
content: 'The following numbers were found:';
display: list-item;
list-style-type: none;
}
#output:empty::before {
content: '';
}
<ul id="output"></ul>
JS Fiddle demo.
Providing a filtered solution to Wei's answer
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var lower = 18;
var upper = 20;
var result = array.filter(function(item) {
return item >= lower && item <= upper;
});
document.getElementById('listOfvalues').innerHTML = ('There are ' + result.length + ' numbers that are between the two numbers);
In short, use the filter function to return results according to your low and high boundaries. Print the length of the returned array of values.
For the if/else statement you can do by yourself.
Edit: Added link to filter
本文标签:
版权声明:本文标题:javascript - Find if numbers in an array are between two numbers and output number of values that are between - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741215897a2360038.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论