I have a Javascript array that can contains duplicates (only 2) having same value for the key color
.
var array = [
{
"id": "1",
"color": "red",
"animal": null
},
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
I'd like to remove duplicates on key color
and only keep the unique object having the key animal
not null
.
var uniqueArray = [
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
var obj = {};
for (var i = 0; i < array.length; i++) {
obj[array[i]['name']] = array[i];
}
var uniqueArray = new Array();
for (var key in obj) {
uniqueArray.push(obj[key]);
}
Here's the result :
var uniqueArray = [
{
"id": "1",
"color": "red",
"animal": "null"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
I don't know how to choose which object I want to keep.
Note : I can't use ES6
I hope the value of animal should be null instead of 'nul' in the first.
var array = [
{
"id": "1",
"color": "red",
"animal": null
},
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
If you want to pick the unique values(objects in this case) based on color,it's better to create another object and put color as a key to get the unique values.
var obj = {};
array.forEach(a => {
if(!obj[a.color] && a.animal) {
obj[a.color] = a;
}
});
Now the object looks like following
Now you get an object containing unique object based on color and more importantly your animal property is not null. You said you can't think of what to choose here. IMO it's better to select the one having a value rather than a null value.
NOTE: the above code gives you an object but you can convert it to an array easily by following. Not entirely sure if Object.values is an es6 feature or not(didn't find anything on docs).
var arr = Object.values(obj);
If you don't like the above solution, you can iterate over the object and push it to an array.
var finalArr = [];
Object.keys(obj).forEach(function(key) {
finalArr.push(obj[key])
});