JCss
JCss

Reputation: 107

Loop trough an array and compare two values from the lowest to the highest value

I want loop trough an array and compare two values which are next to each other, but not after the index like this:

for (var i = 1; i < arr.length; i++) { 
  if (arr[i]-arr[i-1] == 10) {
    // do something
  }
}

Because when the array looks like this:

10, -20, 20, 50

It will compare (I start with "1" in the loop) -20 with 20, and 20 with 50.

What I want is to compare the array like -20 with 10, 10 with 20 and 20 with 50. Also from the lowest to the highest value and then use

if (arr[i]-arr[i-1] == 10)

Upvotes: 0

Views: 79

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44107

What you should do is use Array.prototype.sort() like so:

var arr = [10, -20, 20, 50];
var sorted = arr.sort((a, b) => a > b);
console.log(arr);
console.log(sorted);

Then you can use your logic on it:

var arr = [10, -20, 20, 50];
var sorted = arr.sort((a, b) => a > b);
for (var i = 1; i < sorted.length; i++) {
    if (sorted[i] - sorted[i - 1] == 10) {
        console.log("Do something");
    }
}

Upvotes: 1

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

It would make sense to sort your array first using the built in array.sort method.

let sortedArr = arr.sort((a, b) => (a - b))

This will put your array in ascending order (lowest to highest), allowing you to do your comparison more cleanly.

Upvotes: 1

Related Questions