2

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

2 Answers 2

2

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

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

Comments

0

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

Comments

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.