Skip to content Skip to sidebar Skip to footer

Count Number Of Values In Array Between Two Input Values

As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the array w

Solution 1:

You can create an extremely clean solution to this problem by utilizing the second property of Array#filter (which sets the this binding given to your callback of choice):

var array = [1, 4, 6, 7, 8, 6]

functioninRange (x) {
  returnthis[0] <= x && x <= this[1]
}

var result = array.filter(inRange, [5, 7]).lengthconsole.log('Total number of values:', result)

Solution 2:

All you need is a simple for loop.

var total = 0;
var num1 = 5;
var num2 = 7;
vararray = [1,4,6,7,8,6];
for(var a = 0; a < array.length; a++) {
    if(array[a] >= num1 && array[a] <= num2) {
         total++;
    }
}
alert("Total numbers of values = " + total);

This will loop through the array, detect nums within the range, tally up a value, and output it in a alert.

Solution 3:

You can use Array.prototype.filter(), RegExp.prototype.test() with RegExp constructor with class from-to, where from is 5, to is 7, get .length of resulting array

varfrom = 5;
var to = 7;
var len = arr.filter(RegExp.prototype.test.bind(newRegExp(`[${from}-${to}]`))).length;

You can alternatively use .toString(), .match()

var arr = [1,4,6,7,8,6];
varfrom = 5;
var to = 7;
var res = arr.toString().match(newRegExp(`[${from}-${to}]`, "g"));
var len = res.length;

console.log(res.length);

Solution 4:

You may do as follows;

var arr = [1,4,6,7,8,6],
  input = [5,7],
 result = arr.reduce((r,n) => n >= input[0] && n <= input[1] ? ++r : r, 0);
console.log(result);

Solution 5:

var array = [1, 4, 6, 7, 8, 6];

functioncountNumber(arr,a,b){
    let count = 0;
    for (const number of arr){
        if (number >= a && number <= b){
            count ++;
        }
    }
    return count;
}

console.log(countNumber(array, 5, 7));

Post a Comment for "Count Number Of Values In Array Between Two Input Values"