Marco
Marco

Reputation: 76

Simplify array from many values to fewer

I have an array with many numbers (165) and want to 'simplify' the array to fewer numbers (50). The reduced array should still be representative for the 165 original numbers.

For example: If I had this array with 8 values [2, 4, 3, 8, 1, 4, 9, 3] and would ask to reduce it to 4 values, I want to receive this array [3, 5.5, 2.5, 6]

Currently I have a function that works when the reduced number and the original number can be divided (as with 8 and 4) but when I try using it with let's say 165 values that should be simplified to 50 values it returns me 54 values:

const array = [28, 71, 64, 116, 128, 8, 78, 172, 142, 96, 12 ... 165 values]
const valuesToSum = Math.floor(array.length / 50); // 50 is the wanted array length 
for (let i = 0; i < array.length; i++) {
    if (i % valuesToSum !== 0 || i === 0) {
        sum += array[i];
    } else {
        returnArray.push(sum / valuesToSum);
        sum = 0;
    }  
}
return returnArray;

In the end this should be a JavaScript function but if someone could explain me this on a mathematical level it would help me a lot.

Upvotes: 0

Views: 418

Answers (1)

Barmar
Barmar

Reputation: 782407

In order to get the exact number of groups you want, you can't round off the number of elements to group. For instance if you want to reduce from 165 to 50, some of the groups will have 3 elements, some will have 4.

To do this, use nested loops. The outer loop increments by the size of the group, while the inner loop increments by 1 within the group. The rounding happens when you convert this inner index to the array index.

const array = [28, 71, 64, 116, 128, 8, 78, 172, 142, 96, 12]

function reduceArray(array, newSize) {
  const returnArray = [];
  const valuesToSum = array.length / newSize;
  for (let i = 0; i < array.length; i += valuesToSum) {
    let sum = 0;
    let j;
    let start_i = Math.floor(i);
    for (j = start_i; j < Math.min(start_i + valuesToSum, array.length); j++) {
      sum += array[j];
    }
    returnArray.push(sum/(j - start_i));
  }
  return returnArray;
}

console.log(reduceArray(array, 4));

const bigArray = [];
for (let i = 0; i < 165; i++) {
  bigArray.push(Math.floor(Math.random() * 200));
}
let result = reduceArray(bigArray, 50);
console.log(result.length);
console.log(result);

Upvotes: 1

Related Questions