Skip to content

Instantly share code, notes, and snippets.

@Erenor
Last active May 23, 2018 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Erenor/3676bf610432d97680e19b9fc01e4edb to your computer and use it in GitHub Desktop.
Save Erenor/3676bf610432d97680e19b9fc01e4edb to your computer and use it in GitHub Desktop.
[JAVASCRIPT] Function to remove duplicate items from an array of objects, using "key" as comparison (other keys are not considered)
/**
* Function to remove duplicate items, using "key" as comparison (other keys are not considered)
*/
function ereUniques(arr, key) {
var len = arr.length;
var seen = [];
var final = [];
var finalCounter = 0;
var i, innerItem;
for (i = 0; i < len; i++) {
innerItem = arr[i][key];
if (seen[innerItem] !== 1) {
seen[innerItem] = 1;
final[finalCounter++] = arr[i];
}
}
return final;
}
//test array (last two elements have the same "date")
var testArray = [{"date":"2018-05-22T14:01:25+00:00","wtt":"93.7314"},{"date":"2018-05-22T16:38:25+00:00","wtt":"94.0171"},{"date":"2018-05-22T16:38:25+00:00","wtt":"94.0171"}];
var result = ereUniques(testArray, 'date');
//result should be
//[{"date":"2018-05-22T14:01:25+00:00","wtt":"93.7314"},{"date":"2018-05-22T16:38:25+00:00","wtt":"94.0171"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment