Skip to content Skip to sidebar Skip to footer

Normalizing Data Using Javascript

I have multiple arrays of size 262144, and I am trying to use the following code to set all the values of each array to between 0 and 1, inclusive. To be clear, each array will be

Solution 1:

Your code works fine for me. The following example results in the following normalized array:

[
  0,
  0.821917808219178,
  0.0684931506849315,
  0.3835616438356164,
  1
]

Note that min and max do not have to be between 0 and 1 since they represent the minimal and maximal value of your original array.

var array = [4, 64, 9, 32, 77];

var i;
var max = Number.MIN_VALUE;
var min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++)
{
   if(array[i]>max)
   {
       max = array[i];
   }
}

for (i = 0; i < array.length; i++)
{
   if(array[i]<min)
   {
       min = array[i];
   }
}

for (i = 0; i < array.length; i++)
{
   var norm = (array[i]-min)/(max-min);
   array[i] = norm;
}

max = Number.MIN_VALUE;
min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++) {
    if(array[i]>max) {
        max = array[i];
    }
}

for (i = 0; i < array.length; i++) {
    if(array[i]<min) {
        min = array[i];
    }
}

console.log(array);

console.log(max); // 1console.log(min); // 0

Edit: As you can see in the example, the min and max value after the normalization should be 0 and 1, which is the case.

Solution 2:

I found the solution thanks to this answer! It's simply that the numbers were being compared as I had not converted them from strings to floats.

Post a Comment for "Normalizing Data Using Javascript"