lodash orderBy doesn't like string variables?

My lodash orderBy isn’t working like I expected.

  let what = ''
  let order = ''

  return _.orderBy(f,[function(o) {

    switch(form.sortOrder) {
        case "Alphabetic" :
          what = o.title;
          order = 'asc';
          break;
        case "Popularity" :
          what = o.popularity;
          order = 'desc';
          break;
        case "Revenue" :
          what = o.revenue;
          order = 'desc';
          break;
        case "Release Date" :
          what = o['release date'];
          order = 'desc';
          break;
    }
    return what }], order)

When the form is used to change the sort order, it doesn’t change the order and sticks with ‘asc’ sorting.

@saneef sent me this functional solution. Thanks

found = {
  let arr = BMovies;
  const { sortOrder } = form;

  const order = sortOrder !== "Alphabetic" ? "desc" : "asc";
  const keyMap = new Map([
    ["Alphabetic", "title"],
    ["Popularity", "popularity"],
    ["Revenue", "revenue"],
    ["Release Date", "release date"]
  ]);

  arr = _.orderBy(arr, keyMap.get(sortOrder) ?? keyMap("Alphabetic"), order )

  return arr;
}
2 Likes