Find if numbers in an array are between two numbers and the output number of values ​​that are between

I've been trying over the last few hours to find out how to find numbers in an array that are between two 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 whatever 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 would go crazy if I tried to do it myself.

+3


source to share


5 answers


You can check if the value is in the given range and read 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);
      

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

Run codeHide result


How Array#reduce

does it work in this case?

You have an accumulator for the result, denoted as r

and the actual iteration value denoted as a

. The returned result is the sum of the previous invoice and ckeck if the value is in the given range.

    r       a   return   comment
------  ------  ------  --------
    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 ES6 style.

You can use a callback for Array#reduce

with a closure above lower

and upper

for example

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

Run codeHide result


or you can use a function that takes an array, lower

and upper

, and returns the bill.

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

Run codeHide result


0


source


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

      



+2


source


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

      

+2


source


One approach is as follows:

// 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 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>
      

Run codeHide result


JS Fiddle demo .

+1


source


Providing a filtered solution for 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 a filter function to return results that match your high and low bounds. Print the length of the returned array of values.

For the if / else statement, you can do it yourself.

Edit: Added link for filtering

0


source







All Articles