0

I would like to iterate over the array and getting an average from 5 next elements, not from the whole array. I try to do it by code bellow, but it doesn´t work. I appreciate any kind of help or suggestions.

 function standardDeviation(array) {
        let newArray = [];
        for (let i = 0; i < array.length; i++) {
          let tempArray = []; 
          const arrAvg = tempArray =>
            tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
          newArray += tempArray;

          for (let j = array[i]; (j = array[i + 5]); i++) {
            tempArray += array[j];
          }
        }
        console.log(newArray);
        return newArray;
      }
      var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      standardDeviation(arr);
3
  • What is the purpose of j = array[i + 5]? Commented Feb 27, 2019 at 14:52
  • 1
    please add the wanted result. Commented Feb 27, 2019 at 14:54
  • I guess you want for(let j = i; j < array.length && j < i + 5; j++) in the inner loop Commented Feb 27, 2019 at 14:55

2 Answers 2

2

You could slice a given array and take only five elements for getting an average.

function standardDeviation(array) {
    const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
    return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));

Sign up to request clarification or add additional context in comments.

Comments

0

You could try using the slice() function of array element.

// simulated loop index
var curr_index_pos = 3; 
// entire array
var array_full = [1,2,3,4,5,6,7,8,9,10]; 

// array with 5 next values from "curr_index_pos"
var array_5 = array_full.slice(curr_index_pos,curr_index_pos+5); 

var sum = 0;
for( var i = 0; i < array_5.length; i++ ) {
   sum += parseInt( array_5[i] ); 
}

var avg = sum/array_5.length;

console.log("array_5", array_5);
// [4,5,6,7,8]
console.log("sum", sum);
// 30
console.log("avg", avg);
// 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.