1

I have an array of task objects containing previous and next task ids. I need to display an array of tasks which are sorted based on previous and next task ids. For example:

My input task array is

 [
    {
    "taskId": "101",
    "previousTaskId":"0",
    "nextTaskId":"102"
    },

    {
    "taskId": "103",
    "previousTaskId":"102",
    "nextTaskId":"0"
    },

    {
    "taskId": "102",
    "previousTaskId":"101",
    "nextTaskId":"103"
    }
]

My output task array is:

[
    {
    "taskId": "101",
    "previousTaskId":"0",
    "nextTaskId":"102"
    },

    {
    "taskId": "102",
    "previousTaskId":"101",
    "nextTaskId":"103"
    },

    {
    "taskId": "103",
    "previousTaskId":"102",
    "nextTaskId":"0"
    }
]

Is there any way to implement it using es6 methods? I am trying to use reduce and map functionality

const sortedTasks = tasks.reduce((acc, task) => {
    let {taskId, previousTaskId, nextTaskId} = task;
    return {...acc, task.map(function(item){
        if(item.previousTaskId === 0) //first position
            //how to compare with another taskId and assign it to acc ?

         })
    };
}, {});

3
  • what baout zero as id? do you have always zero at start and end? Commented May 31, 2021 at 10:18
  • Why don't you use built in sort function? Commented May 31, 2021 at 10:19
  • The input array is coming from an ajax call and yes the first object.previousTaskId is always 0 and endObject.nextTaskId is 0 Commented May 31, 2021 at 10:27

1 Answer 1

2

You could build a reference from each predecessor to the node and build the result from zero.

function sort(array) {
    const
        temp = data.reduce((t, o) => {
            t[o.previousTaskId] = o;
            return t;
        }, {}),
        result = [];
    
    let p = '0';
    while (temp[p]) {
        result.push(temp[p]);
        p = temp[p]?.taskId;
    }
    return result;
}

const
    data = [{ taskId: "101", previousTaskId: "0", nextTaskId: "102" }, { taskId: "103", previousTaskId: "102", nextTaskId: "0" }, { taskId: "102", previousTaskId: "101", nextTaskId: "103" }];

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

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

3 Comments

Thanks a lot . Just to understand the code, I usually use ternary operator with ? followed by : I am slightly confused, What does this line mean p = temp[p]?.taskId;
I see. If a reference is null or undefined, the expression short-circuits with a return value of undefined, instead of causing an error. Thanks

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.