0

I want to group items based on date.

To show note items in html same date have same have same group.

Filter method works but how to take also date.

It looks like your post is mostly code; please add some more details.

const [noteData,setNoteData]=React.useState([{
    id: Math.random(),
    headline:"sample 1",
    innerText:"lorem ipsum sit dolar ametlorem ipsum sit dolar ametghbjknlmşöds asopıhgpduhfgopa doırg oıdsğoınrgh ğıhsğoın ğoısğ orıo sğı oo ",
    date:"25.02.2022"
  },{
    id:Math.random(),
    headline:"sample 2",
    innerText:"",
    date:"24.02.2022"
  },{
    id:Math.random(),
    headline:"sample 6",
    innerText:"lorem ipsum sit dolar amet",
    date:"23.02.2022"
  },])
  const [secondNoteData,setSecondNoteData]=React.useState([])

  //* local storage get notes
  React.useEffect(()=>{
    const localNotes=JSON.parse(localStorage.getItem('react-note-app-data'));
    if(localNotes){

      setNoteData(localNotes)
    }
    console.log(localNotes)
  },[])

  React.useEffect(()=>{
    setSecondNoteData(noteData)
  },[noteData])

  //* local storage set notes
  React.useEffect(()=>{
    if (noteData) { // added if check, to check wether noteData variable has value if yes then set the value in localStorage else not.
      localStorage.setItem('react-note-app-data',JSON.stringify(noteData))
  }  },[noteData])
   
  //* item return new array depends date 

  //* notes

  const notess= secondNoteData.filter((item)=>{
    return item.date== "25.02.2022"
    //* this return based on spesicfic date
    //* ı wanna grupize depends on date.
    })

    console.log(notess)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
polmayan
  • 41
  • 4
  • What is the expected result? – Mina Jul 29 '22 at 08:00
  • If you are able to use Lodash, maybe this will help you: https://stackoverflow.com/questions/23600897/using-lodash-groupby-how-to-add-your-own-keys-for-grouped-output – zrna Jul 29 '22 at 08:49

1 Answers1

0

You can use reduce to create nested objects:

const notess = secondNoteData.reduce((acc, item) => {
    const date = item.date;
    acc[date] = acc[date] ? acc[date].push(item) : [item];
    return acc;
}, {})

this will return an object where each key is a date, and the value will be an array of all notes of the same date, for example:

{
    "25.02.2022": [{...item}, {...item}]
    "anotherDate": [{...item}]
}
raz-ezra
  • 514
  • 1
  • 15
  • acc not defined, but actuallly ı don t get it, ı know reduce but is there any simple value. ı just wanna order notes with their date and make it outomatic – polmayan Jul 29 '22 at 11:14
  • Oh, you said "I want to group items based on date", I thought that was what you meant. You can use `sort` and use a custom function to order by the date – raz-ezra Jul 30 '22 at 07:31