Gracie williams
Gracie williams

Reputation: 1145

Normalisation of numbers using javascript

I want to normalise the numbers to range of 0 to 10 .. with outlier exclusion.

Example:

var arr = [100,200,19,0,200,12,20000]

normalise(arr,200); // should be 10
normalise(arr,12); // should be 0.6

// My expected output for above array:
[5, 10, 0.95, 0, 10, 0.6, 10]

Below is the sample code using python , which is exactly what I am looking for.

 arr = np.array([100,200,19,0,200,12,20000])
 upper_lim = np.median(arr) * 2
 arr_adj = np.where(arr>upper_lim, upper_lim, arr) / upper_lim
 arr_adj *= 10

I tried to convert it to javascript like below , I am new to javascript.

function normalise(arr, value) {
  var arr = [100, 200, 19, 0, 200, 12, 20000]
  var upperlimit = median(arr) * 2;
  //I am struck here 
  return normal * 10;
}

function median(numbers) {
  var median = 0,
      count = numbers.length;

  numbers.sort();

  if (count % 2 === 0) { // is even
    median = (numbers[count / 2 - 1] + numbers[count / 2]) / 2;
  } else { // is odd
    median = numbers[(count - 1) / 2];
  }

  return median;
}

normalise(arr, 200); // should be 10  

Please help me convert this to javascript, thank you.

np.where(arr>upper_lim, upper_lim, arr) / upper_lim;

Upvotes: 0

Views: 119

Answers (1)

MrFreezer
MrFreezer

Reputation: 1843

By default, the sort method sorts elements alphabetically.

function normalise(arr,value)
{
    var count = arr.length;
    arr.sort((a, b) => a - b);
    if (count % 2 === 0) {  // is even
    median = (arr[count / 2 - 1] + arr[count / 2]) / 2;
      } else { // is odd
    median = arr[(count - 1) / 2];
   }
    var upper_lim = median*2;
    //console.log(upper_lim);
    /*for ( i = 0; i < count; i++ ) {
        arr[i] = 10*Math.min(arr[i], upper_lim )/upper_lim;
    }
    console.log(arr);
    */

    return  10*Math.min(value, upper_lim )/upper_lim;
}
var arr = [100,200,19,0,200,12,20000]
console.log(normalise(arr,200)); // should be 10

Upvotes: 1

Related Questions