Below is the input array I have:
let inputArr = [
{
"supplierId": "1",
"baseSupplierId": "71277",
"supplierName": "Supplier 1",
"partNumber": "4018992",
"partDescription": "Description 1"
},
{
"supplierId": "2",
"baseSupplierId": "71277",
"supplierName": "Supplier 2",
"partNumber": "4018992",
"partDescription": "Description 2"
},
{
"supplierId": "3",
"baseSupplierId": "71277",
"supplierName": "Supplier 3",
"partNumber": "4019030",
"partDescription": "Description 3"
},
{
"supplierId": "4",
"baseSupplierId": "71277",
"supplierName": "Supplier 4",
"partNumber": "4018291",
"partDescription": "Description 4"
},
{
"supplierId": "5",
"baseSupplierId": "71277",
"supplierName": "Supplier 5",
"partNumber": "4018992",
"partDescription": "Description 5"
}
]
And I want to have an array as output which will have unique values based on column "baseSupplierId" and "partNumber" and also if there are multiple records with the same "baseSupplierId" and "partNumber" then get only the first one and remove other duplicates.
So I want the ouput array as follows:
let outputArr = [
{
// This is the item that had multiple records with the same "baseSupplierId" and "partNumber" and now only one should come in output
"supplierId": "1",
"baseSupplierId": "71277",
"supplierName": "Supplier 1",
"partNumber": "4018992",
"partDescription": "Description 1"
},
{
"supplierId": "3",
"baseSupplierId": "71277",
"supplierName": "Supplier 3",
"partNumber": "4019030",
"partDescription": "Description 3"
},
{
"supplierId": "4",
"baseSupplierId": "71277",
"supplierName": "Supplier 4",
"partNumber": "4018291",
"partDescription": "Description 4"
}
]
2
Answers
Use a set to get uniqueness
Then chain all relevant fields
Insert into output array if not exist in set.
You could convert (using Array.prototype.reduce()) to new Map() (by unique property) and then extract the Map’s
.values()
: