Select-All on Current Sorted Page in a Table

Struggled with this for a while so thought I'd share. This code lets you select-all on the currently shown page, even after sorting the table.

This is pretty ugly, would be interested to hear if there was a better solution!

//if there is no sorting applied, it is simple
if (tableName.sort.length == 0){
  tableName.selectRow(_.range(tableName.paginationOffset,tableName.paginationOffset + tableName.pageSize));
  return false;
}

//first sort the table as it's sorted on the front-end
let sortedTable = _.sortBy(tableName.displayedData,tableName.sort[0].id);
let firstDisplayedRow = tableName.paginationOffset;
//filter to just the records on this currently shown page
let thisSortedPage = _.values(_.pickBy(sortedTable,function(value,key){return (key >= firstDisplayedRow) && (key <= (firstDisplayedRow + tableName.pageSize - 1))}));
//create an array of just the ids of the records in this current page (or use whatever column exists in your data)
let selectTheseIds = thisSortedPage.map(function (o){return o.id});
//now go back to the original unsorted table and filter to just the records with these ids
let showTheseRows = _.pickBy(tableName.displayedData,function(value,key){return selectTheseIds.includes(value.id)});
//this gives the indexes of the original unsorted table that we want to show
let showTheseIndices = _.keys(showTheseRows);
//so we can select them now and it should work!
tableName.selectRow(showTheseIndices);