Home > database >  Extracting a list of ordered numbers from an array in Javascript
Extracting a list of ordered numbers from an array in Javascript

Time:12-18

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

CodePudding user response:

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)

CodePudding user response:

Could be useful:

<?php

$arr = [1, 3, 2, 10, 4, 6, 8];

$result = [];
$currentArray = [];
$previousValue = $arr[0];

foreach ($arr as $value) {
  if ($value > $previousValue) {
    $currentArray[] = $value;
  } else {
    $result[] = $currentArray;
    $currentArray = [$value];
  }
  $previousValue = $value;
}
$result[] = $currentArray;

print_r($result); // Outputs [[1,3],[2,10],[4,6,8]]

?>
  • Related