0

I have an array of columns that represents a row of data in a grid.

It looks something like the following:

let row = [rowId,'string value', 'string value 2', 'string value 3'];

I need to generate a dynamic row of data depending upon a variable number of columns the row will have. In other words, I need the array to be initialized so it contains the id and then X number of columns (depending upon the variable number of columns the grid will have).

[id, 'col-1', 'col-2', ...]

I currently have a ridiculous method which works and looks like the following:

getNewRow(maxKey: number, rowWidth: number){
    switch (rowWidth){
      case 1:{
        return [maxKey, 'col 1'];
        break;  
      }
      case 2:{
        return [maxKey, 'column 1', 'col 2'];
        break;  
      }
      case 3:{
        return [maxKey, 'column 1', 'col 2', 'col 3'];
        break;  
      }
      case 4:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4'];
        break;  
      }
      case 5:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5'];
        break;  
      }
      case 6:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6'];
        break;  
      }
      case 7:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7'];
        break;  
      }
      case 8:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8'];
        break;  
      }
      case 9:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8', 'col 9'];
        break;  
      }
      case 10:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8', 'col 9', 'col 10'];
        break;  
      }
    }

maxKey is just a simple way of insuring that the id column gets set to a new unique value.

My Questions

  • Is it possible to generate a row of data like this dynamically?
  • Is there some way to create a an array on the fly that has a dynamic width (based on the number of columns)?
1
  • Is the discrepency between 'col 1' and 'column 1' deliberate or a typo? Commented Dec 10, 2022 at 3:56

1 Answer 1

2

Create an array of all the cols with their changing index string with Array.from, and then yu can spread that into the returned array.

const getNewRow = (maxKey: number, rowWidth: number) => [
  maxKey,
  ...Array.from(
    { length: rowWidth },
    (_, i) => 'col ' + (i + 1)
  )
];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.