Home > Blockchain >  How to show the data of each month in one row
How to show the data of each month in one row

Time:11-09

Hi I have a list of data stored in an array ,the |arraycontains the list ofobjects`.Each object has certain properties like name,created-at etc. Now I want to show all the users that are created in a particular month ,show in one row,like if the two users are created in the month of November I want to show these two users in one row.having the heading month name and year.

let users[{name: user1, created-at: November},{},{}];

enter image description here

CodePudding user response:

I created an array of unique createdAt values from an users array. Then I mapped this table and added to it every user that has the same creation date

function App() {
  let users = [
    {name: 'user1', createdAt: 'November'},
    {name: 'user5', createdAt: 'November'},
    {name: 'user2', createdAt: 'April'}];
  let rows = [...new Set(users.map(item => item.createdAt))];
  return (
    <div className="App">
      {rows.map(i=><div>
        <h1>{i}</h1>
        <ol>{users.map(j => i === j.createdAt ? <li>{j.name}</li>: null)}</ol>
      </div>)}
    </div>
  );
}

CodePudding user response:

You will need some form of 'groupBy' function in order to achieve this. Have a look at this example.

const users = [{
    firstName: "Garnet",
    createdAt: "January"
  },
  {
    firstName: "Pearl",
    createdAt: "February"
  },
  {
    firstName: "Amethyst",
    createdAt: "January"
  },
  {
    firstName: "Steven",
    createdAt: "March"
  }
]

function groupBy(array, key) {
  return array.reduce((acc, obj) => {
    const property = obj[key]
    acc[property] = acc[property] || []
    acc[property].push(obj)
    return acc
  }, {})
}

console.log(groupBy(users, 'createdAt'))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related