Home > Mobile >  Return a react element containing a value from an array according to another array of integer
Return a react element containing a value from an array according to another array of integer

Time:02-02

I have two array that contains an integer and strings like this.

let intArr = [4,3,2,1]
let player = ['a','b','c','d','e','f','g','h','i','j']

and the sum of intArr will always be the same as player's length

how do i return return a div as much as each number in intArr with player's value inside the div

expected :

since intArr index 0 is 4, the first div should be like this


<div>
   <div> a </div>
   <div> b </div>
   <div> c </div>
   <div> d </div>
</div>

and then for index 1 of intArr which is 3, it should return like this

<div>
   <div> e </div>
   <div> f </div>
   <div> g </div>
</div>

and so on

CodePudding user response:

First we need to group your letters:

let intArr = [4,3,2,1]
let player = ['a','b','c','d','e','f','g','h','i','j']

let acc = 0
const groups = intArr.map(len => {
  acc  = len
  return player.slice(acc - len, acc)
})

The groups now has a value of [['a','b','c','d'],['e','f','g'],['h','i'],['j']]

Then we just output them like this:

return(
  <>
    {groups.map((group, i) => {
      return (
        <div key={i}>
            {group.map((letter, j) => {
              return <div key={j}>{letter}</div>
            })}
        </div>
      )
    })}
  </>
)

CodePudding user response:

If I understand correctly, intArr defines the slice or chunk length for each group in player.

You can get the result you want like this...

let offset = 0;
const slices = [];
for (const len of intArr) {
  slices.push(player.slice(offset, offset   len);
  offset  = len;
}

You can iterate this in JSX to get your divs...

{slices.map((slice, sliceIndex) => (
  <div key={sliceIndex}>
    {slice.map((p, pIndex) => (
      <div key={pIndex}>{p}</div>
    ))}
  </div>
))}

Edit happy-blackburn-d02rf5


If player and intArr are state values, you may want to wrap this in a memo hook so it recalculates if state changes.

const slices = useMemo(() => {
  let offset = 0;
  const arr = [];
  for (const len of intArr) {
    arr.push(player.slice(offset, offset   len);
    offset  = len;
  }
  return arr;
}, [player, intArr]);
  • Related