0

I am trying to optimize a function that will sort a multidimensional array based on user preferences. (id, name, timestamp etc). Instead of creating many different functions i want to combined them all into one. For example see the code bellow. Instead of making 2 different functions i want to be able to pass name or timeCreated strings to it but i don't know how to convert a string into dot notation.

compareName (a, b) {
    if (a.name < b.name) {
        return -1;
    }
    if (a.name > b.name) {
        return 1;
    }
    return 0;
},
compareCreated (a, b) {
    if (a.timeCreated < b.timeCreated) {
        return -1;
    }
    if (a.timeCreated > b.timeCreated) {
        return 1;
    }
    return 0;
}

Because some values could be null i found this function that takes care of things better than the above code...I just need to figure out a way to pass my array selector to the a and b.

alphabetically(ascending) {
  return function (a, b) {
    // equal items sort equally
    if (a === b) {
        return 0;
    }
    // nulls sort after anything else
    else if (a === null) {
        return 1;
    }
    else if (b === null) {
        return -1;
    }
    // otherwise, if we're ascending, lowest sorts first
    else if (ascending) {
        return a < b ? -1 : 1;
    }
    // if descending, highest sorts first
    else { 
        return a < b ? 1 : -1;
    }
  };
}
user1033882
  • 123
  • 1
  • 13

1 Answers1

1

You can use [] notation and accept one extra parameter in your function

alphabetically(ascending) {
  return function (a, b, prop) {
    // equal items sort equally
    if (a[prop] === b[prop]) {
        return 0;
    }
    // nulls sort after anything else
    else if (a[prop] === null) {
        return 1;
    }
    else if (b[prop] === null) {
        return -1;
    }
    // otherwise, if we're ascending, lowest sorts first
    else if (ascending) {
        return a[prop] < b[prop] ? -1 : 1;
    }
    // if descending, highest sorts first
    else { 
        return a[prop] < b[prop] ? 1 : -1;
    }
  };
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60