1

Let's say I have to separate divs and a prop. I need to disseminate the prop to two separate divs. Given the function:

function Collection(props) {
   const coll = props.coll
   const coll_list = coll.map((coll, index) => {
      return (
         <span key={index}>{coll}</span>
      )
   })

   return (
      <div className="main_div">
         <div className="div_a">
            {coll_list}
         </div>
         <div className="div_b">
            {coll_list}
         </div>
      </div>
   )
}

Result should be like this:

<div className="main_div">
   <div className="div_a">
      <span>item_1</span>
      <span>item_2</span>
      <span>item_3</span>
   </div>
   <div className="div_b">
      <span>item_4</span>
      <span>item_5</span>
      <span>item_6</span>
   </div>
</div>

I'll appreciate all the answers. Thanks.

DaOneRom
  • 284
  • 4
  • 18

1 Answers1

2

If you only need to split to 2 lists than you can find the middle and split the array to 2 parts:

function Collection(props) {
   const coll = props.coll.map((coll, index) => (<span key={index}>{coll}</span>));
   const middle = Math.floor(coll.length / 2);
   const coll_list_a = coll.slice(0, middle);
   const coll_list_b = coll.slice(middle, coll.length);

   return (
      <div className="main_div">
         <div className="div_a">
            {coll_list_a}
         </div>
         <div className="div_b">
            {coll_list_b}
         </div>
      </div>
   )
}

If you want a more robust solution to split to parts with n length you can slice the array to chunks and create the lists dynamically:

function chunkify(arr, n){
    let index = 0;
    const len = arr.length;
    const chunks = [];

    for (index = 0; index < len; index += n) {
        chunks.push(arr.slice(index, index + n));
    }

    return chunks;
}

function Collection(props) {
   const coll = props.coll.map((coll, index) => (<span key={index}>{coll}</span>));
   const chunks = chunkify(coll)

   return (
      <div className="main_div">
         {
            chunks.map((list, index) => (
               <div key={index} className={"div_" + index}>
                  {list}
               </div>
            ))
         }
      </div>
   )
}
Lior Hai
  • 477
  • 2
  • 5