d_z90 d_z90 - 14 days ago 9
Javascript Question

Make average of values inside array to smooth graph line

I have an

array
which represents the points of a graph with different values like the following one:

var array = [5, 3, 4, 1, 2];


I would like to loop through it and create a new array where the new values are:


  • An average between the value preceding it and the one coming after it.

  • Placed among the existing ones.



This means that
array[0]
will remain at the same position, while the other values will be pushed of one position. The new array should look like this:

var newArray = [5, 4, 3, 3.5, 4, 2.5, 1, 1.5, 2];


Do you have an idea on how to achieve this? Thanks in advance to your replies!

Answer

var array = [5, 3, 4, 1, 2];
var newArr = [array[0]]; // start the array with the first from the original

array.reduce((a, b) => {
  newArr.push((a + b) / 2, b);
  return b;
});

console.log(newArr);