Reputation: 107
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
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
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