用 JavaScript 從含有影像資料的資料中刪除重複的值


假設我們有一些關於影像的資料,這些資料放在一個類似這樣的陣列中 −

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
}];

我們需要編寫一個 JavaScript 函式,該函式接收一個這樣的陣列。

我們的函式應從陣列中移除那些在 'image' 屬性中具有重複值的專案。

示例

程式碼如下 −

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));

輸出

而控制檯中的輸出將是 −

[
   { image: 'jv2bcutaxrms4i_img.png', gallery_image: true },
   { image: 'abs.png', gallery_image: true },
   { image: 'acd.png', gallery_image: false }
]

更新於: 2020-11-23

381 瀏覽

職業生涯啟動

完成課程獲得認證

開始
廣告