rpsep2
rpsep2

Reputation: 3111

find the closest number which is higher or lower than x

If I have an array which is 'dynamic', e.g:

var xArray = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6]

I need to find the closest number (in terms of INDEX) to the last entry, which is not equal to the last entry (in terms of NUMBER)

Kind of hard to explain! So in the case of the array above, the last entry is 6. I'm looking for the closest entry which is different to 6 (could be higher or lower value). in this case it would be

xArray[11] //7

so at the moment I have:

var lastX = xArray[xArray.length -1],
prevX = ?????

Upvotes: 0

Views: 207

Answers (5)

Tibos
Tibos

Reputation: 27823

A functional solution could be this one:

var array = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6]
var lastIndex = array.reduce(function(acc,item,index,arr){ 
                               return item !== arr[acc] ? index : acc 
                             }, 0) -1;

console.log(lastIndex);

It is not as efficient as the others because it needs to iterate through the entire array.

Upvotes: 0

adeneo
adeneo

Reputation: 318192

Something like :

function diff(arr) {
    var a = arr.slice(), last = a.pop(), nxt = a.pop();
    while (last == nxt && a.length) nxt = a.pop();
    return nxt;
}

FIDDLE

call it like

var diff = diff(xArray);

Upvotes: 3

Aioros
Aioros

Reputation: 4383

function firstDifferent(arr) {
    for (var i=arr.length-2; i>=0; i--) {
        if (arr[i] != arr[arr.length - 1])
            return i;
    }
}

var xArray = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6];
var different = firstDifferent(xArray);

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try this,

var xArray = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6];
var xChangeDetector = null;

for(var I=xArray.length-1; I>=0 ; I--)
{
   if(xChangeDetector == null)
     {
        xChangeDetector = xArray[I];
     }
   else if(xChangeDetector != xArray[I])
     {
        xChangeDetector = xArray[I];
        break;
     }       
}

alert(xChangeDetector);

DEMO

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var xArray = [2, 4, 5, 5, 6, 7, 8, 9, 9, 8, 7, 7, 6, 6, 6]
var index = xArray.length - 1,
    num = xArray[index];
while (--index >= 0 && xArray[index] == num);
console.log(index)
//here num will be 11

Demo: Fiddle

Upvotes: 1

Related Questions