Search code examples
javascriptarraysalgorithmrangereduce

How to create an array of price-ranges from an array of price-values?


I have an array of prices

I would like to group these prices into ranges if they are within 2 of each other

How do I achieve this

// present array
const array = [
   '3','5','6','12','17','22'
]

// the result I want
const array_ranges = [
   '3-6', '12',
  '17','22'
]

Solution

  • You could define an offset of 2 and check the last pair if the delta is greater as this offset and push a new value the result set, otherwise take the value of the first part of the last stored or value and build a new pair.

    const
        array = ['3','5','6','12','17','22'],
        offset = 2,
        result = array.reduce((r, v, i, a) => {
            if (!i || v - a[i - 1] > offset) r.push(v);
            else r.push(`${r.pop().split('-', 1)[0]}-${v}`);
            return r;
        }, []);
    
    console.log(result);