0

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++
   }
}
4
  • arrayOfNumbers [i] === arrayOfNumbers [i + 1] arrayOfNumbers [i + 1] === arrayOfNumbers [i + 2] arrayOfNumbers [i + n] === arrayOfNumbers [i + n + 1] you can use a for-loop Commented Jun 29, 2022 at 19:12
  • 1
    Compare for what? Sorting? If so, the best way is to use Array.sort: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 29, 2022 at 19:12
  • Comparing them to see if they're trending in an upwards or downwards trajectory . Commented Jun 29, 2022 at 19:19
  • I used a for loop because the array size may change depending on the data source. Commented Jun 29, 2022 at 19:20

2 Answers 2

1

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]);

Sign up to request clarification or add additional context in comments.

Comments

0

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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.