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"
}
]
asked Feb 26, 2022 at 12:19
Zain Khan
1,8946 gold badges45 silver badges78 bronze badges
-
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.T.kowshik Yedida– T.kowshik Yedida2022年02月26日 12:21:57 +00:00Commented Feb 26, 2022 at 12:21
-
basically, the objects are coming from s3 bucketZain Khan– Zain Khan2022年02月26日 12:24:22 +00:00Commented Feb 26, 2022 at 12:24
-
I'm using s3 as storage and getting the document objects.Zain Khan– Zain Khan2022年02月26日 12:25:07 +00:00Commented 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.T.kowshik Yedida– T.kowshik Yedida2022年02月26日 16:14:25 +00:00Commented Feb 26, 2022 at 16:14
1 Answer 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" } ]) );
answered Feb 26, 2022 at 12:25
Majed Badawi
28.5k4 gold badges30 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js