I am facing difficulty in deleting duplicate data from localStorage, the platform use JavaScript on Cordova-Phone Gap, how can I delete duplicate data on localStorage ?
For example remove duplicate by ID :
[{ID=1, NAME:"JAMES"},
{ID=1, NAME:"JAMES"},
{ID=2, NAME:"HENRY"},
{ID=3, NAME:"JOHN"},
{ID=3, NAME:"JAMES"}]
Expect :
[{ID=1, NAME:"JAMES"},
{ID=2, NAME:"HENRY"},
{ID=3, NAME:"JOHN"}]
In your specific example, where you wish to remove any objects with the same numerical
ID, you can use a for-each loop to transfer the object stored in each element to the element index of an empty array only if an object has not already been sent to the index that shares itsIDin your case, since you have no
ID:0, the first element of the no-duplicate array will be undefined (and should be removed byfiltering).Here is a working example (I replaced
=with:in your objects). This will keep only the first object of each IDIf, instead of the first object for a given ID you want the last, simply remove
if (!nonDuplicatedData[x.ID])from theforEachloop to keep replacing the object, leaving the final occurence for that ID number.Obviously, your
localStorageversion will have to be retrieved,JSON.parsed into an object and assigned to a variable (datahere). After filtering, you'd have toJSON.stringifyit before putting it back tolocalStorage. Also, this requires numeric IDs, it is not a general solution.