Daniel Bailey
Daniel Bailey

Reputation: 989

Possible to find previous number in array different to current?

I currently have a items that have item levels that are pushed into an array each time a function runs. I wanted to know if say for instance the current number is 2, if there is a way to go back along the item levels I currently have in my array and check what the last number was in the array that was different to 2.

So if it finds a 3, 4, 6, 1000 etc. then it will return that because that number is not equal to the current number. I have included a screenshot of my final array result in order to possibly help with the big picture.

Also I would prefer that it goes back along the array and stops when it finds a different number, because otherwise it would just be a simple each loop that will check if any number in the array is different.

I have tried to think of a way to do this but I cannot think of a solution. Thanks in advance.

My Array Result

Upvotes: 0

Views: 49

Answers (2)

Steve Archer
Steve Archer

Reputation: 641

I'm not sure what you mean by the 'current' number, so let's just say it's any arbitrary index that you want it to be. In that case,

function findPreviousDifferent(array, current) {
    for(let i=current-1; i>=0; i--) {
        if(array[current] !== array[i])
            return array[i];
    }
    return null;
}

That should do it, if I'm understanding what you want correctly. I dunno what you want it to do if every previous element is equal to current, or if current is the first element for that matter, so it'll just return null.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370989

A straightforward solution would be to use a loop that iterates starting from the last index, and returns the value at the first index from the right for which the value is different from the value at the last index:

const arr = [1, 2, 2, 3, 1, 1, 2, 3, 1, 1, 1];

function findLast() {
  const lastNum = arr[arr.length - 1];
  for (let i = arr.length - 2; i >= 0; i--) {
    if (arr[i] !== lastNum) return arr[i];
  }
}

console.log(findLast())

A less efficient but more readable solution would be to reverse the array and .find:

const arr = [1, 2, 2, 3, 1, 1, 2, 3, 1, 1, 1];

function findLast() {
  const lastNum = arr[arr.length - 1];
  return [...arr].reverse().find(item => item !== lastNum);
}

console.log(findLast())

Or, even better, when pushing to the array, check to see if the item being pushed is different than the last value, and if it is, set variables lastValue and nextToLastValue appropriately. Then, when you need nextToLastValue, just access it.

Upvotes: 1

Related Questions