Skip to content
Advertisement

Extracting a list of ordered numbers from an array in Javascript

I have an array for example arr = [1,3,2,10,4,6,8] I want to extract the list of ordered numbers in that array so the result of my example is S = [[1,3],[2,10],[4,6,8]]

another example arr = [13,89,81,17,7,27,5] the result has to be S = [[13,89],[81],[17],[7,27],[5]]

// main function
function mainFunction(arr) {
  // console.log(arr);
  let rowLength = arr[0].length;
  let j =0
  let s = [];
  let se = [];
  let tab = [];
  for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
    while(j<rowLength) {
      while (arr[i][j + 1] <= arr[i][j]) {
        tab = arr[i].splice(j + 1);
        se = arr[i];
        s.push(se);
        arr[i]=tab
      }
      j++
    }
  }
}

Advertisement

Answer

You can keep track of the previous item, and if the current is greater, push to the last array in the result. Otherwise, push a new array:

const arr = [1, 3, 2, 10, 4, 6, 8]
const result = [[arr[0]]]

let last = arr[0]
for (let i = 1; i < arr.length; i++) {
  const curr = arr[i];
  if (curr > last) {
    result[result.length - 1].push(curr)
  } else {
    result.push([curr])
  }
  last = curr
}

console.log(result)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement