Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract numbers sequence from array?

Tags:

javascript

I have the following array :

var selectedRange = [
  null,
  null,
  null,
  null,
  null,
  null,
  null,
  null,
  9, //sequences
  10,//sequences
  null,
  12,
  13,
  14,
  null,
  null,
  null,
  null,
  null,
  20,
  null,
  null,
  null,
  null,
  25,
  null,
  null,
  null,
  29,
  30,
  31,
  32,
  null,
  null,
  null,
  null,
  37,
  38,
  null,
  40,
  41,
  42,
  null,
  44,
  null,
  null,
  47,
  null,
  49,
  50,
  null,
  null,
  null,
  null,
  null,
  null
]

I need to extract sequences of number and only numbers - so the result would be like:

["9,10", "12,13,14", "20", "25", "29,30,31,32", "44", "47", "49,50"]

The problem is that I can't come up with a solution to extract a sequence as it is, I guess I need a recursive function that repeats the part of checking if the last number and the current are following - like here ...(!!prm && (prm - (index-1) ==1 )

let tempArr = [];
$.each(selectedRange, function (index, prm) {
    if (!!prm && (prm - (index - 1) == 1) {
        tempArr.push(prm); // need to loop this section with recursion 
    }
});
like image 574
RoyBarOn Avatar asked Sep 19 '26 17:09

RoyBarOn


2 Answers

One option is to join into a comma delimited string and then split apart the empty elements. Add a final filter to remove leading or trailing empty elements. This might not be the most efficient.

var selectedRange = [null, null, null, null, null, null, null, null, 9, 10, null, 12, 13, 14, null, null, null, null, null, 20, null, null, null, null, 25, null, null, null, 29, 30, 31, 32, null, null, null, null, 37, 38, null, 40, 41, 42, null, 44, null, null, 47, null, 49, 50, null, null, null, null, null, null ]

console.log(
  selectedRange.join(',').split(/,,+|^,|,$/).filter(Boolean)
)  

(Edited to incorporate comment-suggestions from @KooiInc and @Ifaruki.)

like image 91
user650881 Avatar answered Sep 21 '26 11:09

user650881


You could iterate the array and have a look to the predecessor.

let selectedRange = [null, 8, null, null, null, 9, 10, null],
    result = [],
    last;

for (const value of selectedRange) {
    if (value === null) continue;
    if (last + 1 === value) result[result.length - 1] += `,${value}`;
    else result.push(value.toString());
    last = value;
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 43
Nina Scholz Avatar answered Sep 21 '26 11:09

Nina Scholz