let arr = [
{ name: '', value: '2', type: '1' },
{ name: '', value: '3', type: '1' },
{ name: '', value: '3', type: '1' },
{ name: '', value: '2', type: '1' },
{ name: '', value: '4', type: '1' },
{ name: '', value: '5', type: '1' }
];
let arrD = [];
const map = new Map();
arr.forEach(v => {
if (map.get(v.name) && arrD.every(vD => vD.name != v.name)) {
arrD.push(v);
} else {
map.set(v.name, v);
}
}); // arrD = [{name: "", value: "4", type: "1"}]
filter will do
let arr = [
{'name': '' , 'value' : '2', 'type' : '1'},
{'name': '' , 'value' : '3', 'type' : '1'},
{'name': '' , 'value' : '3', 'type' : '1'},
{'name': '' , 'value' : '2', 'type' : '1'},
{'name': '' , 'value' : '4', 'type' : '1'}
];
var aa= arr.filter(function(p){return p.name== '';})[0];
console.log(aa); //{name: "", value: "2", type: "1"}
var bb= arr.filter(function(p){return p.value== '3';})[1];
console.log(bb); //{name: "", value: "3", type: "1"}
let arr = [
{'name': '', 'value': '2', 'type': '1'},
{'name': '', 'value': '3', 'type': '1'},
{'name': '', 'value': '3', 'type': '1'},
{'name': '', 'value': '2', 'type': '1'},
{'name': '', 'value': '4', 'type': '1'},
{'name': '', 'value': '4', 'type': '1'}
]
let resMap = {}
for (let i = 0; i < arr.length; iPP) {
let outItem = arr[i]
if (resMap[outItem.name]) {
resMap[outItem.name].countPP
continue
}
for (let j = i + 1; j < arr.length; jPP) {
let innerItem = arr[j]
if (outItem.name === innerItem.name) {
resMap[outItem.name] = {
value: outItem,
count: 1
}
break
}
}
}
console.log(resMap) // {"":{"value":{"name":"","value":"2","type":"1"},"count":3},"":{"value":{"name":"","value":"3","type":"1"},"count":2}}
let arr = [
{ 'name': '' , 'value' : '2', 'type' : '1'},
{ 'name': '' , 'value' : '3', 'type' : '1'},
{ 'name': '' , 'value' : '3', 'type' : '1'},
{ 'name': '' , 'value' : '2', 'type' : '1'},
{ 'name': '' , 'value' : '4', 'type' : '1'}]
let newarr = arr.filter((item, index, self)=>{
const obj = {}
for(let i = index+1; i < self.length; iPP){
if(self[i].name === item.name || self[i].value === item.value){
return true
}
}
return false
})
console.log(newarr)
idea : this kind of problem belongs to the category of data deduplication, so just redo it according to the data.
effect :
Code :
let arr = [
{ 'name': '' , 'value' : '2', 'type' : '1'},
{ 'name': '' , 'value' : '3', 'type' : '1'},
{ 'name': '' , 'value' : '3', 'type' : '1'},
{ 'name': '' , 'value' : '2', 'type' : '1'},
{ 'name': '' , 'value' : '4', 'type' : '1'},
];
const dataGroup = (dataSource, splitFields) => {
//
return splitFields.reduce( (data, field) => {
// field
data[field] = dataSource.reduce((dataInner, item) => {
dataInner[item[field]] = dataInner[item[field]] || item;
return dataInner;
}, {})
return data;
}, {})
}
console.log( dataGroup(arr, ['name', 'value']) );
Note: if it is not the result you want, you can explain it in the comments.