Giả sử chúng ta có một số dữ liệu về một số hình ảnh trong một mảng như sau:
const arr = [{
'image': "jv2bcutaxrms4i_img.png",
'gallery_image': true
}, {
'image': "abs.png",
'gallery_image': true
}, {
'image': "acd.png",
'gallery_image': false
}, {
'image': "jv2bcutaxrms4i_img.png",
'gallery_image': true
}, {
'image': "abs.png",
'gallery_image': true
}, {
'image': "acd.png",
'gallery_image': false
}];
Chúng ta cần viết một hàm JavaScript nhận một mảng như vậy.
Hàm sẽ xóa các đối tượng khỏi mảng có giá trị trùng lặp cho thuộc tính 'image'.
Ví dụ
Mã thực hiện:
const arr = [{
'image': "jv2bcutaxrms4i_img.png", 'gallery_image': true
}, {
'image': "abs.png", 'gallery_image': true
}, {
'image': "acd.png", 'gallery_image': false
}, {
'image': "jv2bcutaxrms4i_img.png", 'gallery_image': true
}, {
'image': "abs.png", 'gallery_image': true
}, {
'image': "acd.png", 'gallery_image': false
}];
const buildUnique = (arr = []) => {
const unique = [];
arr.forEach(obj => {
let found = false;
unique.forEach(uniqueObj => {
if(uniqueObj.image === obj.image) { found = true; }
});
if(!found){ unique.push(obj); }
});
return unique;
};
console.log(buildUnique(arr));
Kết quả
Kết quả trong console:
[
{ image: 'jv2bcutaxrms4i_img.png', gallery_image: true },
{ image: 'abs.png', gallery_image: true },
{ image: 'acd.png', gallery_image: false }
]