简体   繁体   中英

Sorting an increasing number in an array in Javascript

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') } } 

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); 

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]); } } 

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) 

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]; } } 

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM