I am looking to create a versatile function that can organize an array of objects based on specified keys, while maintaining the order of previous keys. Here is a sample scenario:
const input = [
{ a: 'aardvark', b: 'bear', c: 'camel', d: 1 },
{ a: 'anemone', b: 'bat', c: 'cobra', d: 6 },
{ a: 'aardvark', b: 'badger', c: 'camel', d: 2 },
{ a: 'alligator', b: 'bat', c: 'chicken', d: 2 },
{ a: 'alligator', b: 'beetle', c: 'cow', d: 1 },
{ a: 'alligator', b: 'bat', c: 'crab', d: 3 },
]
sortFunction(['a', 'b', 'd'], input)
// output
[
{ a: 'aardvark', b: 'badger', c: 'camel', d: 2 },
{ a: 'aardvark', b: 'bear', c: 'camel', d: 1 },
{ a: 'alligator', b: 'bat', c: 'chicken', d: 2 },
{ a: 'alligator', b: 'bat', c: 'crab', d: 3 },
{ a: 'alligator', b: 'beetle', c: 'cow', d: 1 },
{ a: 'anemone', b: 'bat', c: 'cobra', d: 6 },
]
The initial sorting key is a
, so the output correctly arranges the data by a
in descending order. The subsequent key in the list is b
, which then reorders items with matching values of a
based on the b
keys. Finally, d
is used to reorder items with identical values of a
and b
. For example, if there are two items with a: alligator
and b: bat
, the item with d: 2
is positioned before the one with d: 3
.
The challenge lies in transforming this specific example into a generic function capable of accepting any array of objects and organizing them according to a defined list of keys, where the values of those keys are either strings or numbers.