javascript – How to distribute numbers from js array

Question:

The task is this:

var streak = {
  min: '',
  max: '',
  length: '',
  series: []
}

var allStreaks = []

I have an array of numbers:

var arr = [19, 20, 21, 22, 17, 18, 19, 7, 8, 9]

I need to distribute them across arrays so that it contains these numbers in ascending order, and write it all in this format:

[{
  min: 19,
  max: 22,
  length: 4,
  series: [19, 20, 21, 22]
}, {
  min: 17,
  max: 19,
  length: 3,
  series: [17, 18, 19]
}, {
  min: 7,
  max: 9,
  length: 3,
  series: [7, 8, 9]
}]

In the original array, the numbers go in the order in which I need them (as if these numbers were going by dates – one number – one day) I need to catch how many "days" these numbers have increased, what date they started and where they stopped and then all over again. The first 4 numbers of the arr array (19 20 21 22) must create an object in which the minimum number (19), the maximum number (22) will be written, how many numbers were written (4) and the array of these numbers itself [19, 20, 21 , 22]. In the same way, with the second increasing streak from 17 to 19, etc. The numbers in the original array are absolutely random and you need to track this sequence of increments and as soon as a number less than the previous one is encountered, start a new array

At the moment I'm doing this:

for (var i = 0; i < arr.length-1; i++) {
  if (arr[i] < arr[i+1]) {
    streak.series.push(arr[i])
  } else {
    streak.series.push(arr[i]) //Сохранит последний элемент первого стрика
    break;
  } 
}

This is how I successfully get the first streak, but if I need to continue, then difficulties arise:

for (var i = 0; i < arr.length-1; i++) {
  if (arr[i] < arr[i+1]) {
    streak.series.push(arr[i])
  } else if ((arr[i] > arr[i-1]) && (arr[i] > arr[i+1])) {
    streak.series.push(arr[i]) // Это ловит и записывает последний элемент первого стрика, получается steak.series = [19,20,21,22]
    // но он на этом не останавливается и продолжает записывать все числа исходного массива
    // так как они потом подходят под первый if (arr[i] < arr[i+1])
    // и в результате у меня просто переписывается весь исходный массив
  } else {continue;} 
}

Answer:

var allStreaks = [];
var arr = [19, 20, 21, 22, 17, 18, 19, 7, 8, 9];
var prevMaxPos = 0;

doWork();
console.log(allStreaks);

// функции работы и заноса в итоговый массив
function doWork() {
  for (var i = 1; i < arr.length; ++i) {
    if (arr[i] < arr[i - 1]) {
      allStreaks.push(setStreak(arr.slice(prevMaxPos, i)));
      prevMaxPos = i;
    }
  }

  if (arr.slice(prevMaxPos).length > 0)
    allStreaks.push(setStreak(arr.slice(prevMaxPos)));
}

function setStreak(arr) {
  return streak = {
    min: arr[0],
    max: arr[arr.length - 1],
    length: arr.length,
    series: arr
  }
}
Scroll to Top