I have created a function that eliminates duplicates from an array, but unfortunately it does not work for arrays of objects. I am struggling to understand why and cannot find any information on how to resolve this issue.
This is the function I have implemented:
function removeDuplicates(array) {
var length = array.length;
if (!length) {
return;
}
var index = 0;
var result = [];
while (index < length) {
var current = array[index];
if (result.indexOf(current) < 0) {
result.push(current);
}
index++;
}
return result;
}
For example:
var my_data = [
{
"first_name":"Bob",
"last_name":"Napkin"
},
{
"first_name":"Billy",
"last_name":"Joe"
},
{
"first_name":"Billy",
"last_name":"Joe",
}
]
removeDuplicates([1, 1, 2, 3]) // => [1, 2, 3]
removeDuplicates(my_data) // => [ { "first_name":"Bob", "last_name":"Napkin" }, { "first_name":"Billy", "last_name":"Joe" }, { "first_name":"Billy", "last_name":"Joe" } ]
Can anyone provide insight into creating a duplicate-free version of an array containing objects?