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

98
Views
Reordering array using .sort with parameters

I have a function to reorder an array with objects inside and I call that function with the object property I want to sort, but I don't know how to set the callback function to use the parameter. I tried use eval() but with no success. It's not working correctly.

function order(param){
  const newOrder = arrayContent.sort((first,second) => (`${first}.${param}` > `${second}.${param}`) ? 1 : -1);
};
order('name')
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It's pretty easy to implement. You can refer to object either with 'dot notation' e.g. object.name or with help of square brackets e.g. object['name'] where you could put any string inside brackets to refer to certain 'inner field'

let arrayContent = [{number:3,name:'Alice'},{number:2, name:'Maxim'}]; //your array
    let order = param => arrayContent.sort((first,second) => first[param] < second[param]?1:-1);
    
    order('name');
    console.log(arrayContent);
    order('number');
    console.log(arrayContent);

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!