Pranay Boga

Pranay Boga

  • 1.6k
  • 82
  • 15.2k

How to display sequence of number and non sequence as abbrevated ?

Dec 8 2022 5:05 PM

For example Given numbers are 1,2,3,4,7,10, 12, 15,16,17,22 then the abbrevated result is 1-4,7,10,12,15-17,22. The solution i got is as following:

arr is the array of number which you want to pass and c = 0

ngOnInit(): void {

    console.log('Entered array: ',this.arr);

    var el = document.getElementById('firstvalue');

    el.innerHTML = this.arr;

    this.combo(this.arr);

  }

  combo(arr) {

    this.result+= arr[0];

    this.formethod(arr, this.c);  //this.c=0;

  }

  formethod(arr, x) {

     for(x;x<arr.length;x++){

      if(x != arr.length -1){

        if(arr[x+1]-arr[x]==1)

        {

          let a=this.result.length;

          if(!(this.result[a-1].includes('-')) && !this.result[a-1].includes(','))

          {

            this.result+='-';

          }

          else if(this.result[a-1].includes(',')){

            if(arr[x+1]-arr[x]==1)

                this.result+=arr[x]+'-';

            else

                this.result+=arr[x];

          }      

        }

        else {

          if(x!=0)

            this.result+=arr[x]+',';

          else this.result+=',';

        }

      }

      else {

        this.result+=arr[x];

      }

     }

  }

 

if you like the answer please support me.

Thank you


Answers (1)