題目描述
找出數(shù)組 arr 中重復(fù)出現(xiàn)過的元素
示例1
輸入
[1, 2, 4, 4, 3, 3, 1, 5, 3]
輸出
[1, 3, 4]
function duplicates(arr) {
var obj = {};
var repeatList = [];
//遍歷數(shù)組,將數(shù)組的值作為obj的索引痰憎,出現(xiàn)次數(shù)為值
arr.forEach(function(item){
if(obj[item]){
obj[item] +=1;
}else{
obj[item] = 1;
}
});
//獲取對象自身屬性
var propertyNames = Object.getOwnPropertyNames(obj);
//遍歷對象缰揪,將重復(fù)出現(xiàn)的元素取出
propertyNames.forEach(function(item){
if(obj[item] > 1){
repeatList.push(parseInt(item));
}
});
return repeatList;
}