简体   繁体   中英

How grouped sort array of objects based on object's value?

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'}];

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM