0

I'm running into a error in stopping the execution when a lower number occurs in the data of an array

Let seat1 = [2, 5, 6, 9, 2, 12, 18];

console should log the values till it gets to 9 since

2 < 5 < 6 < 9 then omit 2 since 9 > 2

then continue from 12 < 18.

let num = [2, 5, 6, 9, 2, 12, 18];
    
    for (let i = 0; i < num.length; i++) {
        if ((num[i] + 1) > num[i]) {
    
            console.log(num[i])
        } else {
            console.log('kindly fix')
        }
    }
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
Tush
  • 19
  • 2

5 Answers5

3

Use Array.reduce() to create a new array without the items that are not larger than the last item in the accumulator (acc) or -Infinity if it's the 1st item:

const num = [2, 5, 6, 9, 2, 3, 12, 18];

const result = num.reduce((acc, n) => {
  if(n > (acc[acc.length - 1] || -Infinity)) acc.push(n);

  return acc;
}, []);

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

simple answer using if and for -

let num = [2, 5, 6, 9, 2 , 3, 12, 16, 9, 18];
let max = 0;

for (let i = 0; i < num.length; i++) 
{ 
   if ((i == 0) || (num[i] > max)) {
     max = num[i];
     console.log (num[i]);
   }
}
Akshay
  • 350
  • 1
  • 7
1

You could filter the array by storing the last value who is greater than the last value.

var array = [2, 5, 6, 9, 2, 3, 12, 18],
    result = array.filter((a => b => a < b && (a = b, true))(-Infinity));

console.log(result)
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • What. What's this? `(a => b => a < b && (a = b, true))(-Infinity)` How is the double arrow working here? never seen that before. Mind explaining it? – briosheje Apr 03 '19 at 14:21
  • @briosheje, it is a closure over `a`, which is invoked with `-Infinity`. `b` is the value of each item in the array. the rest is a condition and a part with a comma operator which returns `true` at the end after assigning `b` to `a`. – Nina Scholz Apr 03 '19 at 14:24
  • Oh. Interesting. So, `a` holds the lowest (current) value in the array, right? never saw that before. Also, didn't know that `(a = b, true)` would return true. Thanks for sharing and explaining. – briosheje Apr 03 '19 at 14:31
  • `a` contains the last valid greater value. – Nina Scholz Apr 03 '19 at 14:34
  • Right, sorry. That's a clever approach. – briosheje Apr 03 '19 at 14:36
0

Store the max value and check num[i] against the current max. If num[i] is bigger, log it and set the new max value. Initial max value should be first num value but smaller so it doesn't fail on the first check.

let num = [2, 5, 6, 9, 2, 12, 18];
let max = num[0] - 1;

for (let i = 0; i < num.length; i++) {
  if (num[i] > max) {
    console.log(num[i]);
    max = num[i];
  }
}
Farzad A
  • 578
  • 1
  • 5
  • 15
-2

let num = [2, 5, 6, 9, 2, 12, 18];
let result = num.sort((a, b) => a - b).filter((elem, pos, arr) => {
     return arr.indexOf(elem) == pos;
  })
 console.log(result)
Nver Abgaryan
  • 621
  • 8
  • 13