1.剔除数组中id相同且name相同的对象元素,将保留前者。
let array=[
{"id":"1","name":"a","age":"18"},
{"id":"2","name":"b","age":"18"},
{"id":"1","name":"c","age":"20"},
{"id":"1","name":"a","age":"30"},
]
for (let i = 0; i < array.length; i++) {
for (let j =i+1; j <array.length; ) {
if (array[i].id=== array[j].id&&
array[i].name=== array[j].name ) {//通过属性进行匹配;
array.splice(j, 1);//去除重复的对象;
}else {
j++;
}
}
}
console.log(array);
// {"id":"1","name":"a","age":"18"},
// {"id":"2","name":"b","age":"18"},
// {"id":"1","name":"c","age":"20"},
2.计算数组中重复出现元素的个数
var arr = ["apple","orange","apple","orange","pear","orange"];
function getWordCnt(){
var obj = {};
for(var i= 0, l = arr.length; i< l; i++){
var item = arr[i];
obj[item] = (obj[item] +1 ) || 1;
}
return obj;
}
console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1}
3.去除数组中changeBillNo相同的对象
let hash = {};
//去除changeBillNo相同的元素
array = array.reduce(function(item, next) {
hash[next.changeBillNo] ? '' : hash[next.changeBillNo] = true && item.push(next);
return item
}, [])