简体   繁体   中英

Get max value from array between certain positions

I'm trying to return a max value from an array, but I only need the max from certain positions in the array: ex.

var array = [1,2,3,4,5] and I'd need the sum of the max of array[0] to array[2] to be summed up to array[3] to array[4] ( so totalScore = max(array[0] ... array[2]) + max(array[3] ... array[4])

is there a way to do that with Math.max.apply? My code below + pen over here: https://codepen.io/stdobrescu/pen/mdJdBbG?editors=1111

  $("input[type='radio']").click(function() {
    var question = document.getElementsByClassName("toggle");
    var totalScore = 0;
    var questionValue = [0];  

    for (i = 0; i < question.length; i++) {
      if (question[i].type == "radio") {
        if (question[i].checked) { 
          questionValue[i] = parseInt(question[i].value, 10);
          }
        highestVal(questionValue);
        totalScore = calcScore(questionValue);
        questionValue = questionValue.filter(n=>n!==undefined);
        $("#score").html(totalScore);
      }
    }
  });

 function highestVal (valueArray){
  valueArray = valueArray.filter(n=>n!==undefined);
  console.log("This is the value array " + valueArray);
  var highestVal = Math.max.apply(null, valueArray);
  console.log("This is the highest value " + highestVal)
  return highestVal;
 }

 function calcScore (scoreArray){

   var sum = scoreArray.reduce((a, b) => a + b, 0)
   console.log("The Sum is "+ sum);
   return sum;
 }

Radio button structure (values go in questionValue array)

<div class="input-control">
          <input id="1" class="toggle" name="1" value=0 type="radio">
          <label for="1" class="btn"><span>0</span> I never take longer than 30 minutes to fall asleep.</label>
          <input id="2" class="toggle " name="1" value=1 type="radio">
          <label for="2" class="btn"><span>1</span> I take at least 30 minutes to fall asleep, less than half the time.</label>
          <input id="3" class="toggle" name="1" value=2 type="radio">
          <label for="3" class="btn"><span>2</span> I take at least 30 minutes to fall asleep, more than half the time.</label>
          <input id="4" class="toggle" name="1" value=3 type="radio">
          <label for="4" class="btn"><span>3</span> I take more than 60 minutes to fall asleep, more than half the time.</label>
        </div>

thanks!

 const sumMax = (arr, ...pos) => pos.map(p => Math.max(...arr.slice(p[0], ++p[1]))).reduce((p, c) => p + c) const myArray = [1, 2, 3, 4, 5] console.log(sumMax(myArray, [0, 2], [3, 4]))


Update based on OP comment

One way to make sumMax a live function is to update your main array everytime new items are added and call sumMax on the updated array (this is not a performance optimized solution, we sometimes compute redundant max and sum, see dynamic programming ). To do so we use closure :

 function liveSumMax (arr, ...pos) { // wrapper function const mainArray = arr const positions = pos const sumMax = (ar, ...ps) => ps.map(p => { let max = Math.max(...ar.slice(p[0], p[1] + 1)) max = max > -Infinity ? max : 0 return max }).reduce((p, c) => p + c) return (...items) => { // live function mainArray.push(...items) // update mainArray return sumMax(mainArray, ...positions) } } const myArray = [1, 2, 3, 4, 5] const sumMax = liveSumMax(myArray, [0, 2], [3, 9]) // returns a function console.log(sumMax()) // no new item console.log(sumMax(10, 20)) console.log(sumMax(30, 40, 50, 60))

You could slice the array, get the sum and the max value from it.

 var add = (a, b) => a + b, array = [1, 2, 3, 4, 5], max = Math.max(array.slice(0, 3).reduce(add), array.slice(3, 5).reduce(add)); console.log(max);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM