I want to find duplicates of objects in an array. I wanna do this by sorting the array and then comparing the items with each other. How can I compare an object "as a string" that means if there is any difference at all they get sorted accordingly?
It's the sort-function I would like to replace.
var newCart = shoppingCart.sort();
var results = [];
for (var i = 0; i < newCart.length - 1; i++) {
if (newCart[i + 1] == newCart[i]) {
results.push(newCart[i]);
}
}
this.products = results;
Example input:
[
{
"id": 1,
"name": "Skateboard",
"price": 1299,
"currency": "SEK",
"thumbnail": "/static/img/products/1-t.jpg"
},
{
"id": 4,
"name": "A trip to the sun with Erik",
"price": 29000,
"currency": "SEK",
"thumbnail": "/static/img/products/4-t.jpg"
},
{
"id": 1,
"name": "Skateboard",
"price": 1299,
"currency": "SEK",
"thumbnail": "/static/img/products/1-t.jpg"
},
{
"id": 4,
"name": "A trip to the sun with Erik",
"price": 29100,
"currency": "SEK",
"thumbnail": "/static/img/products/4-t.jpg"
},
{
"id": 4,
"name": "A trip to the sun with Erik",
"price": 29000,
"currency": "SEK",
"thumbnail": "/static/img/products/4-t.jpg"
},
]
Example output:
[
{
"id": 1,
"name": "Skateboard",
"price": 1299,
"currency": "SEK",
"thumbnail": "/static/img/products/1-t.jpg"
},
{
"id": 1,
"name": "Skateboard",
"price": 1299,
"currency": "SEK",
"thumbnail": "/static/img/products/1-t.jpg"
},
{
"id": 4,
"name": "A trip to the sun with Erik",
"price": 29000,
"currency": "SEK",
"thumbnail": "/static/img/products/4-t.jpg"
},
{
"id": 4,
"name": "A trip to the sun with Erik",
"price": 29000,
"currency": "SEK",
"thumbnail": "/static/img/products/4-t.jpg"
},
{
"id": 4,
"name": "A trip to the sun with Erik",
"price": 29100,
"currency": "SEK",
"thumbnail": "/static/img/products/4-t.jpg"
},
]
Note that the last item in the output ends up last, as the price is not the same as the other items with the same ID.