Reputation: 1404
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 ?
Upvotes: 0
Views: 46
Reputation: 11001
Use filter
and keep track of images with Set
const 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" },
];
const set = new Set();
const galleryFilter = gallery.filter((item) => {
if (
(item?.image?.includes("webp") || item?.image === null) &&
!set.has(item?.image)
) {
set.add(item.image);
return true;
}
});
console.log(galleryFilter)
Upvotes: 0
Reputation: 5264
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);
Upvotes: 1