用 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 }
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP