en6in33r
en6in33r

Reputation: 266

Formula to dynamically calculate .slice() - Javascript

I would like to dynamically render array elements into specified number of columns.

Given an array const sessions = [10, 10, 5] and const trials = [1, 2, 3, ..., 25] where sessions.length is the number of columns and trials is the data.

    <div class="column-1">
      {
          trials.slice(0, 10).map(t => {
            return <p>{t} seconds</p>
          }
      }
    </div>
    <div class="column-2">
      {
          trials.slice(10, 20).map(t => {
            return <p>{t} seconds</p>
          }
      }
    </div>
    <div class="column-3">
      {
          trials.slice(20, 25).map(t => {
            return <p>{t} seconds</p>
          }
      }
    </div>

In column 1, I would display the first 10 elements in trials because sessions[0] = 10. In column 2, I would display the next 10 elements in trials because sessions[1] = 10, and finally the next 5 items because sessions[2] = 5.

My ideal solution would be using something like this where I need to figure out how to calculate x and y based on sessions:

sessions.map((s, idx) => {
    <div class=`column-${idx+1}`>
      {
          trials.slice(x, y).map(t => {
            return <p>{t} seconds</p>
          }
      }
    </div>
}

Upvotes: 1

Views: 389

Answers (2)

user12407908
user12407908

Reputation:

Just keep a running total of the sum of sessions while you .map() the array.

let x = 0;

sessions.map((s, idx) => {
    <div class=`column-${idx+1}`>
      {
          trials.slice(x, x = x + s).map(t => {
            return <p>{t} seconds</p>
          }
      }
    </div>
}

If you don't like using the result of the assignment in the position of an expression, then use a second variable and do the calculation before the markup.

let x = 0;
let y = 0;

sessions.map((s, idx) => {
    x = y;
    y = y + s;

    <div class=`column-${idx+1}`>
      {
          trials.slice(x, y).map(t => {
            return <p>{t} seconds</p>
          }
      }
    </div>
}

Upvotes: 0

AMD
AMD

Reputation: 203

This is what you need to do to calculate the x and y.

sessions.map((s, idx, sessions) => {
   const x = sessions.slice(0, idx).reduce((acc, val) => acc + val, 0);
   const y = x + s;
   return (
      <div class=`column-${idx+1}`>
         {
            trials.slice(x, y).map(t => {
               return <p>{t} seconds</p>
            }
         }
      </div>
   )
}

* sessions in the first callback will be the sessions array. I used the reduce method to calculate the slice's start position.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Upvotes: 1

Related Questions