[Vuejs]-JS Reduce an array evenly

2👍

Since you’re using the first and last values, only 4 steps will actually be taken to receive 5 values (n-1). Let steps be a fractional value representing how many indices to step over between each iteration, starting at 0 and stopping at the highest index in the array.

const range = [8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000]

const values = 5;
const steps = (range.length-1) / (values-1);

let marks=[];
for(let i=0; i<values; i++){
  console.log("Fractional index", i*steps); //just for display purposes
  marks.push(range[Math.round(i*steps)]);
}
console.log(marks);

1👍

Divide your range by n steps. Then step through the list and add the values at each step.

const n=5;
const range = [8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000]

const steps = Math.floor(range.length / n);
const stop = range[range.length - 1];

let marks=[]
for(let i=0;i<n-1;i++){
  marks.push(range[i*steps])
}
marks.push(stop)
console.log(marks);

Leave a comment