Home > front end >  Sort Array with two object inside
Sort Array with two object inside

Time:03-16

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

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

i cant use this

CodePudding user response:

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

CodePudding user response:

Maybe a good idea is to define function that will handle getting properties for the compare purpose?

const handleSort = (arr, desc, getValue) => {
  if (desc) {
    return arr.sort((a,b) => getValue(a) - getValue(b));
  } 

  return arr.sort((a,b) => getValue(b) - getValue(a));

}

In this way, you can use upper function like:

return handleSort(myArray, true, (obj) => obj.foo.foo1.foo2);
  • Related