[Vuejs]-How Vue.js slice data by each group and show 3 rows at top then the other?

0👍

I don’t understand the layout you’ve described, but you are asking about grouping by date so the following code may help.

It’s plain javascript which I import into the Vue component to transform the data after fetch.

The input is an array of objects with a date property to be grouped on. The output is an array of object with two props – date key and a nested array of the grouped objects.

export default {
  filesByDate(files) {
    return filesByDate(files);
  }
}

const filesByDate = (files) => {
  const keyFn = (file) => { return formatDate(file.effectiveDate); };
  return groupBy(files, keyFn)
    .map(group => { return { date: group.key, files: group.group }; });
}

const groupBy = (arr, keyFn) => {
  const grouped = arr.reduce( (grouping, item) => {
    const key = keyFn(item);
    grouping[key] = grouping[key] || [];
    grouping[key].push(item);
    return grouping;
  }, {} );
  return Object.keys(grouped)
    .map(key => { return {key: key, group: grouped[key]}; });
}

const formatDate = (date) => {
  let d = new Date(date);
  let month = '' + (d.getMonth() + 1);
  let day = '' + d.getDate();
  let year = d.getFullYear();
  month = month.length < 2 ? '0' + month : month;
  day = day.length < 2 ? '0' + day : day;
  return [year, month, day].join('-');
}

Leave a comment