D
D
deantek2021-07-05 15:58:12
React
deantek, 2021-07-05 15:58:12

How to properly split an array into chunks?

How to properly split an array in order to put all this stuff into a slider?

60e300a114a44669934758.png

now I get an array with categories, I tried to do it like this

const TopCategories = (props: Props) => {
  const { t, categories } = props

  const cloneArr = categories

  let chunckArr = []
  let size = 8

  while (cloneArr.length > 0) chunckArr.push(cloneArr.splice(0, size))

  const firstSlide = chunckArr[0].map((item) => {
    return (
      <NavLink
        key={item.id}
        to={`/shop/category/${item.slug}`}
        className={`${s.top_categ_item} link external`}
      >
        <div className={s.cart_icon}>
          <img
            src={item.photo_mini ? item.photo_mini : 'photo'}
            alt=""
            onError={(e: any) => {
              e.target.onerror = null
              e.target.src = '/icons/product-without-photo.png'
            }}
          />
        </div>
        <div className={s.cart_name}>{item.name}</div>
      </NavLink>
    )
  })

  const secondSlide = chunckArr[1].map((item) => {
    return (
      <NavLink
        key={item.id}
        to={`/shop/category/${item.slug}`}
        className={`${s.top_categ_item} link external`}
      >
        <div className={s.cart_icon}>
          <img
            src={item.photo_mini ? item.photo_mini : 'photo'}
            alt=""
            onError={(e: any) => {
              e.target.onerror = null
              e.target.src = 'https://cdn.wish.men/icons/product-without-photo.png'
            }}
          />
        </div>
        <div className={s.cart_name}>{item.name}</div>
      </NavLink>
    )
  })

  return (
    <div className={`${s.market__item} ${s.top_category}`}>
      <div className={s.category_title}>{t('shop_page.top_categories')}</div>
      <Swiper
        spaceBetween={5}
        slidesPerView={1}
        containerClass={`${s.swiper_container} ${s.swiper_container_popular}`}
      >
        <div className={s.top_categ_slide_mob}>{firstSlide}</div>
        <div className={s.top_categ_slide_mob}>{secondSlide}</div>
      </Swiper>
    </div>
  )
}

export default TopCategories

it works, but there can be much more categories
, please tell me how to optimize this, because at the moment I can’t find a better solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-07-05
@deantek

Run lodash chunk , and then, as usual, map to map to map.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question