Get used data from selection and getData()

Tags: #<Tag:0x00007f51b5b5ca30> #<Tag:0x00007f51b5b5c8c8>

Hello,

I am trying to get data from a table, but when I call getData() on selected, I get the nested array with [null]s.
Is there a way to get only the used range so only the non null values?

Example:

Selecting the whole column and only wanting the used (non null) values.
I am using React

image

Current output
image

Here is my function to getSelection()

export const getSelection = () => {

  const hot = hotRef.current.hotInstance;
  const selected = hot?.getSelected() || [];

  let data: any[] = [];

  if (selected.length === 1) {
    data = hot?.getData(...selected[0]!) || [];
  }
  
  return data;
};

I know I could build a custom function to find only the non null values but is there a way that is already implemented? I have looked through the documentation and I could not find anything. Maybe my approach is wrong in the first place?

Hi @mario

Thank you for contacting us. The output you get with this solution is actually correct when the whole column is selected. We don’t have any method that would let you get only the cells that have values so a custom implementation is needed in such case. You can also try getDataAtCell in combination with getSelected but again, it will output the data form all currently selected area.

Hi @adrian.szymanski

Thank you for the response. Here is a rapid custom implementation that I did. May not be the best but I hope it helps someone looking for a similar solution get started.

export const getSelection = () => {

  const hot = hotRef.current.hotInstance;
  const selected = hot?.getSelected() || [];

  let data: any[] = [];

  if (selected.length === 1) {
    data = hot?.getData(...selected[0]!) || [];

    // Remove empty rows
    data = data.filter(row => row.some(cell => cell !== null && cell !== ''));

    // Find the rightmost used column if using multiple columns
    let maxColumnIndex = 0;
    data.forEach(row => {
      const lastNonEmptyIndex = row.map(cell => (cell !== null && cell !== '')).lastIndexOf(true);
      if (lastNonEmptyIndex > maxColumnIndex) {
        maxColumnIndex = lastNonEmptyIndex;
      }
    });

    // Slice rows up to the rightmost column and replace nulls with ''
    data = data.map(row => row.slice(0, maxColumnIndex + 1).map(cell => (cell === null ? '' : cell)));

  }
  
  return data;
};

Thanks again!
Mario

@mario

Thank you for sharing your solution :slight_smile: