Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort Array with two object inside

i want to ask about array.sort() was looking for solution about this kind of problem how to sort a array with this kind of structure

  array.sort((a, b) => a.foo.foo1.foo2 - b.foo.foo1.foo2)

where this working but after rewrite the code for multiple use case

export const handleSort = (arr, sortBy, desc) => {
 arr = [...arr];

   if (desc) {
     return arr.sort((a, b) => b[sortBy] - a[sortBy]);
   } else {
     return arr.sort((a, b) => a[sortBy] - b[sortBy]);
   }

later on if i need like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  return arr.sort((a, b) => b[sortBy][0][1] - a[sortBy][0][1]);

i cant use this

>Solution :

You could use a function and an array for getting the right property.

const
    getValue = (object, keys) => keys?.length
        ? keys.reduce((o, k) => o[k], object)
        : object,
    ASC = (a, b) => a - b,
    DESC = (a, b) => b - a,
    sortBy = (order, keys) => (a, b) => order(getValue(a, keys), getValue(b, keys)),
    keys = ['foo', 'foo1', 'foo2'],
    data = [{ foo: { foo1: { foo2: 7 } } }, { foo: { foo1: { foo2: 2 } } }, { foo: { foo1: { foo2: 9 } } }, { foo: { foo1: { foo2: 6 } } }, { foo: { foo1: { foo2: 1 } } }, { foo: { foo1: { foo2: 4 } } }];

// usage
data.sort(sortBy(ASC, keys)); 

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading