Home > Software engineering >  Adding Filtering in an array objects duplicated in existing method
Adding Filtering in an array objects duplicated in existing method

Time:11-24

I have the following array

 [{ id: 1,
    type: 'video',
    image: null,
    url: 'https://www.youtube.com/1'
  },
  { id: 2,
    type: 'video',
    image: null,
    url: 'https://www.youtube.com/2' 
  },
  { id: 3,
    type: 'image',
    image: 'https://example-1.url.webp'
  },
  { id: 4,
    type: 'image',
    image: 'https://example-2.url.jpg',
  },
  { id: 5,
    type: 'video',
    image: 'https://www.youtube.com/2',
  }   
]

I am already filtering all the items who are not webp format and the image is null

  const galleryFilter = gallery.filter(
    (item) => item?.image?.indexOf("webp") === -1 || item?.image === null
  );

As you can see there are 2 items (id 2 and id 5 ) with the same url, how can i also filter the item duplicated with the same url in the galleryFilter method ?

CodePudding user response:

you can append another filter function to filter by image url, (I have added another object into your data set id: 6)

var gallery =  [{ id: 1,
    type: 'video',
    image: null,
    url: 'https://www.youtube.com/1'
  },
  { id: 2,
    type: 'video',
    image: null,
    url: 'https://www.youtube.com/2' 
  },
  { id: 3,
    type: 'image',
    image: 'https://example-1.url.webp'
  },
  { id: 4,
    type: 'image',
    image: 'https://example-2.url.jpg',
  },
  { id: 5,
    type: 'video',
    image: 'https://www.youtube.com/2',
  },
  { id: 6,
    type: 'video',
    image: 'https://www.youtube.com/2',
  }
];

var galleryFilter = gallery.filter( (item) => item?.image?.indexOf("webp") === -1 || item?.image !== null ).filter((item, i, arr) => i == arr.findIndex(e => e.image == item.image));

console.log(galleryFilter);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related