d_z90 d_z90 - 10 months ago 52
Javascript Question

Make average of values inside array to smooth graph line

I have an

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

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;