1

I have the following array of objects:

[
{id: 1, updatedVersion: 7},
{id: 2, updatedVersion: 0},
{id: 7, updatedVersion: 9},
{id: 10, updatedVersion: 11},
{id: 9, updatedVersion: 0},
{id: 11, updatedVersion: 0},
]

Those with updatedVersion equal to zero are the latest versions.

From that array I was able to filter the ones that are the latest version and have at least one previous Version, which are objects with id 9, and 11. (Object with id === 2 is not included since it's the latest version but has no previous versions).

What I need now is to create an extra property in those two objects with id 9 and 11 (again: the objects that are latest version and have at least one previous version), called versionHistory, which would be an ordered array of previous versions of that object, from most recent to oldest.

So it would look something like that:

[
    {   id: 9, 
        updatedVersion: 0, 
        versionHistory: [
            {id: 7, updatedVersion: 9},
            {id: 1, updatedVersion 7}
        ]
    },
    {
        id: 11,
        updatedVersion: 0,
        versionHistory: [
            {id: 10, updatedVersion: 11}
        ] 
    }
]

I came up with an ugly solution that involves nested for loops but I'm looking for something more elegant that uses map, filter and reduce. I would appreciate any hints on how to approach this.

1 Answer 1

1

This isn't terribly efficient but hopefully meets the "elegant" requirement ;)

data = [
    {id: 1, updatedVersion: 7},
    {id: 2, updatedVersion: 0},
    {id: 7, updatedVersion: 9},
    {id: 10, updatedVersion: 11},
    {id: 9, updatedVersion: 0},
    {id: 11, updatedVersion: 0},
]

let prev = node => data.find(n => n.updatedVersion === node.id);

let path = node => node ? [node, ...path(prev(node))] : [];

let result = data.filter(n => n.updatedVersion === 0).map(node => ({
    versionHistory: path(node).slice(1),
    ...node,
}));

console.log(result);

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

Comments

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.