i have array of objects and i want to remove objects which not repeating by property of name.
[
{
"name": "Storage Capacity",
"value": "64GB"
},
{
"name": "Manufacturer Color",
"value": "Black / Red / White / Green / Purpule"
},
{
"name": "Carrier",
"value": "Unlocked"
},
{
"name": "Carrier",
"value": "AT&T"
},
{
"name": "Brand",
"value": "Apple"
},
{
"name": "MPN",
"value": "NA"
},
{
"name": "Model",
"value": "Iphone 11"
},
{
"name": "Color",
"value": "Black"
},
{
"name": "Color",
"value": "White"
},
{
"name": "Storage Capacity",
"value": "128GB"
},
]
final result must be array of objects only with name : color, storage capacity, carrier
CodePudding user response:
We can use Array.reduce()
to calcuate the appear count of each name,then using Array.filter()
to remove the uncessary data.
// calcuate the appearance of each name
let dmap = data.reduce((a,{name}) => {
a[name] = (a[name]??0) 1
return a
},{})
// filter the appear count
let result = data.filter(d => dmap[d.name] > 1)
console.log(result)
let data = [
{
"name": "Storage Capacity",
"value": "64GB"
},
{
"name": "Manufacturer Color",
"value": "Black / Red / White / Green / Purpule"
},
{
"name": "Carrier",
"value": "Unlocked"
},
{
"name": "Carrier",
"value": "AT&T"
},
{
"name": "Brand",
"value": "Apple"
},
{
"name": "MPN",
"value": "NA"
},
{
"name": "Model",
"value": "Iphone 11"
},
{
"name": "Color",
"value": "Black"
},
{
"name": "Color",
"value": "White"
},
{
"name": "Storage Capacity",
"value": "128GB"
},
]
let dmap = data.reduce((a,{name}) => {
a[name] = (a[name]??0) 1
return a
},{})
let result = data.filter(d => dmap[d.name] > 1)
console.log(result)
CodePudding user response:
Could you try this :
var values = [
{
"name": "Storage Capacity",
"value": "64GB"
},
{
"name": "Manufacturer Color",
"value": "Black / Red / White / Green / Purpule"
},
{
"name": "Carrier",
"value": "Unlocked"
},
{
"name": "Carrier",
"value": "AT&T"
},
{
"name": "Brand",
"value": "Apple"
},
{
"name": "MPN",
"value": "NA"
},
{
"name": "Model",
"value": "Iphone 11"
},
{
"name": "Color",
"value": "Black"
},
{
"name": "Color",
"value": "White"
},
{
"name": "Storage Capacity",
"value": "128GB"
},
];
var names = values.map(function(item){ return item.name });
let duplicated_names = names.filter((item, index) => names.indexOf(item) !== index)
let result = [];
for(let row of values) {
if (duplicated_names.includes(row.name)) {
result.push(row);
}
}
console.log(result);