Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

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 함수를 작성해야 합니다.

우리 함수는 '이미지' 속성에 대해 중복 값을 가진 객체를 배열에서 제거해야 합니다.

예시

이에 대한 코드는 -

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