Home > Software engineering >  Sorting over an object passing the search value via a callback results in undefined
Sorting over an object passing the search value via a callback results in undefined

Time:02-12

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

CodePudding user response:

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

  • Related