Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering of the array of objects

I’m trying to filter the array:

const arr = [
{
  id: '1',
  modifiedTime: '2022-08-11T12:30:36.191Z',
  modifiedUser: 'test'
},
{
  id: '2',
  modifiedTime: '2022-08-11T12:30:36.191Z',
  modifiedUser: 'test'
},
{
  id: '2',
  modifiedTime: '2022-09-12T12:30:36.191Z',
  modifiedUser: 'test'
},
{
  id: '3',
  modifiedTime: '2022-08-11T12:30:36.191Z',
  modifiedUser: 'test'
},
];

to get results:

const arr = [
{
  id: '1',
  modifiedTime: '2022-08-11T12:30:36.191Z',
  modifiedUser: 'test'
},
{
  id: '2',
  modifiedTime: '2022-09-12T12:30:36.191Z',
  modifiedUser: 'test'
},
{
  id: '3',
  modifiedTime: '2022-08-11T12:30:36.191Z',
  modifiedUser: 'test'
},
];

so, I need to filter the array in that way to stay with objects without duplicates, when an object has a duplicate, it should get only one with the largest modifiedTime.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was trying to do this in that way:

arr.reduce((arr, el) => (((arr.find(({id}) => el.id === id)) || arr.push(el)), arr), [])

but in this way, it returns to me an array without objects with duplicates id but modifiedTime is not the largest.

Maybe someone will be able to suggest it to me?

>Solution :

You have 3 cases :

  • If the item is not in the array, simply push it
  • If the item is already but has a smaller time : don’t do anything
  • If the item is already but has an higher time : replace the item with the new one

This can be done using the js splice method

const arr = [{
    id: '1',
    modifiedTime: '2022-08-11T12:30:36.191Z',
    modifiedUser: 'test'
  },
  {
    id: '2',
    modifiedTime: '2022-08-11T12:30:36.191Z',
    modifiedUser: 'test'
  },
  {
    id: '2',
    modifiedTime: '2022-09-12T12:30:36.191Z',
    modifiedUser: 'test'
  },
  {
    id: '3',
    modifiedTime: '2022-08-11T12:30:36.191Z',
    modifiedUser: 'test'
  },
];

console.log(
  arr.reduce((acc, curr) => {
    const index = acc.findIndex(x => x.id === curr.id)
    if(index === -1) acc.push(curr)
    else {
      if(new Date(acc[index].modifiedTime) < new Date(curr.modifiedTime))
        acc.splice(index, 1, curr)
    }
    
    return acc
  }, [])
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading