Hi All,
Today I am gonna write down the logic for a topic which is mentioned below.
To display the given array of mixed numbers in which some numbers will be in sequence and some will be random. So to display those sequence number in the form of range and random numbers separated by comma(,) here below I have written the required logic to get the output as mentioned.
Normally this is a small requirement in the project which I am working on. After trying for some time I got this idea and wrote the logic. I wanted to share the knowledge with you.
So writing this blog.
Here code starts,
for (x; x < arr.length; x++) {
var pattern = /^[0-9a-zA-Z]+$/;
let fN0;
if (x != arr.length - 1) {
if (x != arr.length - 2) fN0 = pattern.test(arr[x + 2]) ? parseInt(arr[x + 2].replace(/[^0-9]+/ig, "")) : parseInt(arr[x + 2]);
let fN1 = pattern.test(arr[x + 1]) ? parseInt(arr[x + 1].replace(/[^0-9]+/ig, "")) : parseInt(arr[x + 1]);
let fN2 = pattern.test(arr[x]) ? parseInt(arr[x].replace(/[^0-9]+/ig, "")) : parseInt(arr[x]);
if (fN1 - fN2 == 1 || fN1 - fN2 == 0) {
let a = this.result.length;
if (!(this.result[a - 1].includes('-')) && !this.result[a - 1].includes(',')) {
this.result = fN0 - fN1 == 1 ? this.result += '-' : this.result += ',';
} else if (this.result[a - 1].includes(',')) {
if (fN1 - fN2 == 1) this.result = fN0 - fN1 == 1 ? this.result += arr[x] + '-' : this.result += arr[x] + ',';
// this.result+=arr[x]+'-';
else this.result += arr[x];
}
} else {
if (x != 0) this.result += arr[x] + ',';
else this.result += ',';
}
} else if (arr.length > 1) {
this.result += arr[x];
}
}
return this.result;
In the above logic what we are doing is in the for loop we are taking x value as 0 and here 'arr' is the array that contains all mixed numbers. I have regex expression in pattern variable, this is for if any value in array contains alphanumeric numbers also. Before starting the loop I am assigning the first value in the array to the result variable. In for loop, I am taking first element and then comparing with next element in the array if the difference is 1 then I am considering them as in sequence then adding hyphen (-) to the main string which is result. After that I am taking next element if the next element and its next element are in not in sequence then I am adding this number along with comma(,). This continues until the last element if it is the last element I am directly adding that to the result.