V
V
Vladislav2015-11-14 16:26:05
JavaScript
Vladislav, 2015-11-14 16:26:05

How to convert a sorted array of elements into an array with sequence descriptions?

Converting a sorted array of elements to an array of objects of the form
{key,with,before}
Example

function([a,a,a,a,b,b,b,b,c,c]){
 ...
} // [{key:a,with:0,before:3},{key:b,with:4,before:7},{key:c,with:8,before:9}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2015-11-14
@vlad008

For such transformations, it is convenient to use reduce:

[a,a,a,a,b,b,b,b,c,c].reduce(function(s, e, i) {
    var t = s.pop() || {key: e, with: i};
    if (t.key !== e) {
        s.push(t);
        t = {key: e, with: i};
    }
    t.before = i;
    s.push(t);
    return s;
}, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question