Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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"
    }
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!