bobby_turks
bobby_turks

Reputation: 95

Comparing numerical values of an array against eachother javascript

let arrayOfNumbers = [1, 2, 3, 4, 5]

What would be the best way to compare the numbers against each other ? For instance, comparing 1 to 2 then 2 to 3 then 3 to four, and so on ?

function t(a) {
  let t = 0
  for (let i = 0; i < a.length; i++) {
    if (a[t] > a[t + 1]) {
      console.log('down')
    } else if (a[t] < a[t + 1]) {
      console.log('up')
     } else if (a[t] === a[t + 1]) {
       console.log('no change')
     }
     t++
   }
}

Upvotes: 0

Views: 56

Answers (2)

IT goldman
IT goldman

Reputation: 19485

If you want to pick up trend then you can do a linear regression.

function linearRegression(y, x) {
  var lr = {};
  var n = y.length;
  var sum_x = 0;
  var sum_y = 0;
  var sum_xy = 0;
  var sum_xx = 0;
  var sum_yy = 0;

  for (var i = 0; i < y.length; i++) {

    sum_x += x[i];
    sum_y += y[i];
    sum_xy += (x[i] * y[i]);
    sum_xx += (x[i] * x[i]);
    sum_yy += (y[i] * y[i]);
  }

  lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
  lr['intercept'] = (sum_y - lr.slope * sum_x) / n;
  lr['r2'] = Math.pow((n * sum_xy - sum_x * sum_y) / Math.sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y)), 2);

  return lr;
}


function find_next(arr) {
  var y = [];

  for (var i = 0; i < arr.length; i++) {
    y.push(i);
  }

  var reg = linearRegression(y, arr)
  // y = a*x + b
  // x = (y-b)/a
  var next = (arr.length - reg.intercept) / reg.slope
  return next
}

console.log(find_next([1, 2, 3, 4, 5]))
console.log(find_next([0, 1, 3, 2, 4, 4, 2]))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You could start from index one and check the previous value.

function t(a) {
  for (let i = 1; i < a.length; i++) {
    if (a[i - 1] > a[i]) console.log('down');
    else if (a[i - 1] < a[i]) console.log('up');
    else console.log('no change');
  }
}

t([0, 1, 3, 2, 4, 4, 2]);

Upvotes: 1

Related Questions