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

131
Views
Sorting over an object passing the search value via a callback results in undefined

I have multiple 'sort options' that id like to pass to make this function re-usable, but all passed strings result in undefined when being used to target the objects key. If I hard code the value - name - then it will sort properly. Thanks!

const sortNames = [
  { name: "Maddox", age: 69 },
  { name: "John", age: 69 },
  { name: "Alex", age: 69 },
  { name: "Mike", age: 69 },
];

const sortSomeStuff = (param) => {
    const result = sortNames.sort((a, b) => {
    const paramA = a.param.toLowerCase();
    const paramB = a.param.toLowerCase();

    if (paramA > paramB) {
      return -1;
     }
    if (paramA < paramB) {
      return 1;
    }
    return 0;
  });
  return result;
 };

console.log(sortSomeStuff("name"));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

To have a variable to map an object use [] like this. Also added sort directions.

const sortNames = [
  { name: "Maddox", age: 20 },
  { name: "John", age: 69 },
  { name: "Alex", age: 69 },
  { name: "Mike", age: 69 },
];

const sortSomeStuff = (param, dir="asc") => {
    const result = sortNames.sort((a, b) => {
    var paramA = a[param].toString().toLowerCase();
    var paramB = b[param].toString().toLowerCase();
    if(dir=="dsc"){
      paramA = b[param].toString().toLowerCase();
      paramB = a[param].toString().toLowerCase();
    }
    if (paramA < paramB) {
      return -1;
     }
    if (paramA > paramB) {
      return 1;
    }
    return 0;
  });
  return result;
 };

console.log(sortSomeStuff("age","dsc"));

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!