[英]JavaScript remove single entries from an array of objects
我有这样的结构:
var arr = [
{
title: 'anchorman'
},
{
title: 'happy gilmore'
},
{
title: 'anchorman'
}
]
现在我要做什么才能得到一个像这样的数组:
var arr = [
{
title: 'anchorman'
}
]
因此,它不仅删除唯一的条目,而且只留下一个重复条目。
到目前为止,我已经知道了,但是效果不好!
var ref;
for(var i in movies) {
ref = movies[i].title;
if(this.titles.indexOf(ref) == -1) {
movies.splice(i, 1);
} else {
this.titles.push(ref);
}
}
其中“电影”是该问题的第一个数组,而this.titles只是一个空数组。
以下代码将创建具有所需结果的新数组: jsfiddle
var arr = [
{
title: 'anchorman'
},
{
title: 'happy gilmore'
},
{
title: 'anchorman'
}
];
var temp = {}, newArr = [];
for(var k =0;k< arr.length; k++){
if(temp[arr[k].title]){
newArr.push(arr[k]);
}
temp[arr[k].title] = true;
}
arr = newArr;
//console.log(newArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.