Home > other >  Trying to get full results using DayJs
Trying to get full results using DayJs

Time:05-24

I'm trying to get the full results of this code execution, Right now what I get is only the date's of all values, but I need it so that all columns are displayed, so name and date. Can anyone help?

const result = [
    { id: 1, name: 'Tom', date: '2022-05-17T22:00:00.000Z' },
    { id: 2, name: 'Joe', date: '2022-05-12T22:00:00.000Z' },
    { id: 3, name: 'Frederiko', date: '2022-05-23T22:00:00.000Z' },
    { id: 4, name: 'John', date: null },
    { id: 5, name: 'Boer', date: '2022-05-23T22:00:00.000Z' }
  ]
  
let time = dayjs().format('YYYY-MM-DD')
let eyy = result.filter(item1 => !result.find(item2 => item1.name == item2.name && dayjs(item2.date).format('YYYY-MM-DD') == time))

console.log(eyy);
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>

CodePudding user response:

The result.filter method can be simplified by removing the use of result.find, for example...

const result = [
    { id: 1, name: 'Tom', date: '2022-05-17T22:00:00.000Z' },
    { id: 2, name: 'Joe', date: '2022-05-12T22:00:00.000Z' },
    { id: 3, name: 'Frederiko', date: '2022-05-23T22:00:00.000Z' },
    { id: 4, name: 'John', date: null },
    { id: 5, name: 'Boer', date: '2022-05-23T22:00:00.000Z' }
  ]
  
let time = dayjs().format('YYYY-MM-DD')
let eyy = result.filter(item => dayjs(item.date).format('YYYY-MM-DD') === time)

console.log(eyy);
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>

It's probably worth noting that depending where you are in the world the above will most likely not return anything because there are no dates matching today's date (May 24th).


From your comments it appears you want to modify the structure of the filtered results. To do this you can use the .map() method...

const result = [
    { id: 1, name: 'Tom', date: '2022-05-17T22:00:00.000Z' },
    { id: 2, name: 'Joe', date: '2022-05-12T22:00:00.000Z' },
    { id: 3, name: 'Frederiko', date: '2022-05-23T22:00:00.000Z' },
    { id: 4, name: 'John', date: null },
    { id: 5, name: 'Boer', date: '2022-05-24T22:00:00.000Z' }
  ];
  
let time = dayjs().format('YYYY-MM-DD');
let eyy = result.map(item => {
  return {
    name: item.name,
    date: dayjs(item.date).format('YYYY-MM-DD')
  };
});
    eyy = eyy.filter(item => item.date === time);
    

console.log(eyy);
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>

  • Related