Skip to content

Instantly share code, notes, and snippets.

@francescozanoni
Created March 27, 2020 14:32
Show Gist options
  • Save francescozanoni/3803dfd425e077f9adcb1f797141e806 to your computer and use it in GitHub Desktop.
Save francescozanoni/3803dfd425e077f9adcb1f797141e806 to your computer and use it in GitHub Desktop.
[JS] Make unique the items of an array
/**
* Callback that makes unique the items of an array.
*
* Example usage:
* var myArray = ['a', 1, 'a'];
* var myUniqueArray = myArray.filter(onlyUnique);
*
* @param arrayItem one of the items of the array
* @param {number} arrayIndex
* @param {Array} arrayToMakeUnique
*
* @returns {boolean}
*
* @see https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates
*/
onlyUnique: function (arrayItem, arrayIndex, arrayToMakeUnique) {
const arrayOfJsonizedItems = arrayToMakeUnique.map(JSON.stringify);
const jsonizedItem = JSON.stringify(arrayItem);
return arrayOfJsonizedItems.indexOf(jsonizedItem) === arrayIndex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment