Zain Khan
Zain Khan

Reputation: 1814

Array items sorting in javascript

I have an array that will change in its sorting order of items after each and every call but I wanted them to be fixed as per my requirement on the client side. Example attached below.

array, for example, the indexes or the sorting order won't be the same, it changes every time

[
    {
        key: "foo"
    },
    {
        key: "bar"
    },
    {
        key: "baz"
    }
]

and this is what I want every time, no matter what the sorting order is.

[
    {
        key: "baz"
    },
    {
        key: "foo"
    },
    {
        key: "bar"
    }
]

Upvotes: 1

Views: 46

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28404

Define the "priority" of every key in an object pre hand. Then, using Array#sort, reorder the array:

const priorities = { baz: 3, foo: 2, bar: 1 };

const reorder = (arr = []) =>
  arr.sort(({ key: a }, { key: b }) => priorities[b] - priorities[a]);

console.log( reorder([ { key: "foo" }, { key: "bar" }, { key: "baz" } ]) );
console.log( reorder([ { key: "bar" }, { key: "foo" }, { key: "baz" } ]) );
console.log( reorder([ { key: "baz" }, { key: "bar" }, { key: "foo" } ]) );

Upvotes: 1

Related Questions