-2

I am having array of data Ex. var arr = [1,2,3,4,5,7,8,10,11,12,15]. If array of data number sequence match to range like more than two digits. I want to display above array of data as below. result = [1-5,7,8,10-12,15].

Can any one help me how can i achieve above result in JavaScript.

5
  • what have you tried? how would you solve this problem manually? Commented Oct 31, 2017 at 18:12
  • So, you are going from integer values in the array to string values? Commented Oct 31, 2017 at 18:12
  • Well array of numbers cannot have - inside it Commented Oct 31, 2017 at 18:12
  • is there any way to achieve this? out will be either array or string object. Commented Oct 31, 2017 at 18:15
  • This sentence is very difficult to understand. "If array of data number sequence match to range like more than two digits". Please clarify. Commented Oct 31, 2017 at 18:56

2 Answers 2

1

You could check if a number is in range, the change the last string or push the value to the result set.

1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 15
^                                    no predecessor, push value
+  ^  +                              predecessor and successor, change last value
      +  +  ^                        predecessor and previous predecessor, change last

var array = [1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 15],
    result = [];

array.forEach(function (a, i, aa) {
    result.push(aa[i - 1] + 1 === a && (aa[i - 2] + 1 === aa[i - 1] || a + 1 === aa[i + 1])
        ? [result.pop().split('-')[0], a].join('-')
        : a.toString());
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for giving solution it's helped me to sort out from problem
0

One way to do it

function getRanges(array) {
  let ranges = [], rstart, rend;
  for (let i = 0; i < array.length; i++) {
    rstart = array[i];
    rend = rstart;
    while (array[i + 1] - array[i] == 1) {
      rend = array[i + 1];
      i++;
    }
    ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
  }
  return ranges;
}

const range1 = getRanges([1,2,3,4,5,7,8,10,11,12,15]);
console.log(range1);
const range2 = getRanges([1,2,3,5,7,9,10,11,12,14 ]);
console.log(range2);
const range3 = getRanges([1,2,3,4,5,6,7,8,9,10])
console.log(range3);

1 Comment

in the first example, 7 and 8 should not be together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.