evan2160
evan2160

Reputation: 39

Counting Array Values by a Filtered Value in Javascript

I am trying to count the number of values in the array I calculated (const C) that fall into a given range, for instance the array returns [2,2,1.5,1.5], I'm trying to count the number of values in the array that is <1, 1<x<2, 2<x, etc. So it should return, count x<1 = 0, 1<x<2 = 4, 2<x = 0. Thanks for the help!

for(let i = 0; i < 1; i++) {
   Array.prototype.zip = function (other, reduce, thisArg) {
      var i, result = [], args,
      isfunc = typeof reduce == "function",
      l = Math.max(this.length, other.length);

      for (i = 0; i < l; i++) {
         args = [ this[i], other[i] ];
         result.push( isfunc ? reduce.apply(thisArg, args) : args );
      }
      return result;
   }

   const A = [4,6,12,18]
   const B = [2,3,4,6]
   const C = A.zip(B, function (l, r) { return l / (l - r); }); //[2,2,1.5,1.5]

   let id = document.querySelectorAll(`[id^="id"]`)[i]
   let problemTypeChoice = 0;

   if (problemTypeChoice === 0) {
      id.innerText = `${C}`
   }
}

Upvotes: 1

Views: 42

Answers (1)

IT goldman
IT goldman

Reputation: 19493

Array reduce to group "by" method.

var arr = [2, 2, 1.5, 1.5, 3, -2]
var result = arr.reduce(function(agg, item) {
  var key = "other";
  if (item < 1) key = "<1";
  if (item > 1 && item < 2) key = "1<2";
  if (item > 2) key = ">2";
  agg[key] = (agg[key] || 0) + 1
  return agg;
}, {})

console.log(result)

Upvotes: 1

Related Questions