skip to Main Content

I am working with Office.js development, you don’t need to know anything about it since the question relates more to Javascript. In Excel you can get a matrix of formulas with a function, that is an array of arrays.

Usually there are A LOT of empty values and only couple filled values. Now, I want to find these filled values with their indexes.

Is it possible to do this in Javascript with less then O(n * m) complexity given a matrix (n * m)

Thanks

I can’t think of a solution other than one by one looping through each cell in the matrix.

2

Answers


  1. Chosen as BEST ANSWER

    For Office.js I have found an easier solution. Instead of looking at matrix of formulas. There is a function that let's you get cells by type.

    range.getSpecialCells("Formulas", "All");

    With this i am directly getting a list of formulas.


  2. You might consider using Array.prototype.reduce() to achieve this. However, to find these values, you’ll need to examine each element at least once, so the complexity won’t be lower than O(n * m) in the worst case.

    Here’s an example of how you might do it using reduce():

    function findNonEmptyIndices(matrix) {
      return matrix.reduce((acc, row, rowIndex) => {
        row.forEach((cell, colIndex) => {
          if (cell !== null && cell !== undefined && cell !== '') {
            acc.push({ rowIndex, colIndex, value: cell });
          }
        });
        return acc;
      }, []);
    }
    
    // Example usage:
    const myMatrix = [
      [null, '', 5, null],
      [8, null, '', 10],
      ['', 20, null, 'hello'],
    ];
    
    const nonEmptyIndices = findNonEmptyIndices(myMatrix);
    console.log(nonEmptyIndices);

    This function findNonEmptyIndices() loops through each element of the matrix using reduce(). When it encounters a non-empty cell, it records its row index, column index, and value into an array of objects. This way, you end up with an array containing the indices and values of non-empty cells.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search