The situation that I'm dealing with is that I have an array of objects and I would like to filter down to an array where the objects are unique with regard to one property keeping the last instance.
For example lets say I have an array of files like so:
let files =
[
{
filename: "filename.txt",
uploadedBy: "Bob",
comment: "Gee whiz"
},
filename: "filename.txt",
uploadedBy: "Jane",
comment: "Golly"
},
filename: "otherFile.txt",
uploadedBy: "Bob",
comment: "Shucks"
},
filename: "filename.txt",
uploadedBy: "Henry",
comment: "Gee Willikers"
},
]
I want the objects with distinct filenames and I want the last instance of each filename.
[
filename: "otherFile.txt",
uploadedBy: "Bob",
comment: "Shucks"
},
filename: "filename.txt",
uploadedBy: "Henry",
comment: "Gee Willikers"
},
]
Is there a concise way of doing this? All I can come up with is a pretty long method to first map
the array to get just the filenames, then find the last instance of each filename or something.
The following question is similar but keeps the first value not the last : Get all unique values in a JavaScript array (remove duplicates)
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']