1

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"
    }
]
4
  • As I see, there is no particular order on the pairs. Add a priority or order key to each pair. So that you can sort based on that. Commented Feb 26, 2022 at 12:21
  • basically, the objects are coming from s3 bucket Commented Feb 26, 2022 at 12:24
  • I'm using s3 as storage and getting the document objects. Commented Feb 26, 2022 at 12:25
  • Are those constant values? If it's dynamic, it is not possible to update priority if many such key pairs are present. May be you have to keep a separate table with priorities and update the keys based on that. Commented Feb 26, 2022 at 16:14

1 Answer 1

1

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" } ]) );

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

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.