1

I have array of objects like this:

var points = [{a: 4, b: 3, c:'parent'}, {a: 1, b:5, c:'child'}, {a: 5, b: 2, c:'child'}, {a: 1, b: 2, c:'parent'}, {a: 3, b: 1, c:'child'}];

I need to sort it on "a" object's value. But the problem is if it has the "c" object's value "parent" the "c" object's value "child" should be next object of that and shouldn't be sorted.

At last I expect to have this sorted points array:

var sortedPoints = [{a: 1, b: 2, c:'parent'}, {a: 3, b: 1, c:'child'} ,{a: 4, b: 3, c:'parent'}, {a: 1, b:5, c:'child'}, {a: 5, b: 2, c:'child'}];

1 Answer 1

1

You need to group parents and children, sort and get a flat array.

var points = [{ a: 4, b: 3, c: 'parent' }, { a: 1, b: 5, c: 'child' }, { a: 5, b: 2, c: 'child' }, { a: 1, b: 2, c: 'parent' }, { a: 3, b: 1, c: 'child' }],
    sorted = points
        .reduce((r, o) => {
            if (o.c === 'parent') r.push([o]);
            else r[r.length - 1].push(o);
            return r;
        }, [])
        .sort(([{ a }], [{ a: b }]) => a - b)
        .flat();

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

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

2 Comments

You did it exactly on "a" and "b" object. What should I do for sorting if I have so many more keys on array's objects?
just take .sort(a, b) => ...) and get the needed properties from a and b without destructuring.

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.