E
E
Erl2021-01-19 07:37:55
Vue.js
Erl, 2021-01-19 07:37:55

How to take the first 5 elements in each category?

<template v-for="article in articles">
          <article
            v-if="article.category.name == data.name"
            :key="article.id"
            class="article-thumb"
          >

There is such a code, here I scatter the articles into categories, how can I stop the output of articles if there are already 5 items in the category, I could write something like v-for="article in articles.slice(0, 5)", but then the categories more than 1, and it’s impossible to know for sure, since a different number of articles in categories

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ReaverJS, 2021-01-19
@NooBiToo

Something like:
StackOverflow

let articlesGroups = articles.reduce((articles, item) => {
  let article = (articles[item.category] || []);
  article.push(item);
  articles[item.category] = article;
  return articles;
}, {});

Then bypass articlesGroups - 2 cycles. External - bypasses groups, internal - articles. In the internal one, just put a limit on 5 articles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question