Remove Duplicate data In Localstorage

256 Views Asked by At

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"}]
1

There are 1 best solutions below

0
Dave Pritlove On

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 its ID

in your case, since you have no ID:0, the first element of the no-duplicate array will be undefined (and should be removed by filtering).

Here is a working example (I replaced = with : in your objects). This will keep only the first object of each ID

let data = [
{ID:1, NAME:"JAMES"},
{ID:1, NAME:"JAMES"},
{ID:2, NAME:"HENRY"},
{ID:3, NAME:"JOHN"},
{ID:3, NAME:"JAMES"}
];

const nonDuplicatedData = [];

data.forEach(x => {
if (!nonDuplicatedData[x.ID]) nonDuplicatedData[x.ID] = x;
});

const filteredData = nonDuplicatedData.filter(n => {return n != undefined});

console.log(filteredData);

If, instead of the first object for a given ID you want the last, simply remove if (!nonDuplicatedData[x.ID]) from the forEach loop to keep replacing the object, leaving the final occurence for that ID number.

let data = [
{ID:1, NAME:"JAMES"},
{ID:1, NAME:"JAMES"},
{ID:2, NAME:"HENRY"},
{ID:3, NAME:"JOHN"},
{ID:3, NAME:"JAMES"}
];

const nonDuplicatedData = [];

data.forEach(x => {
nonDuplicatedData[x.ID] = x;
});

const filteredData = nonDuplicatedData.filter(n => {return n != undefined});

console.log(filteredData);

Obviously, your localStorage version will have to be retrieved, JSON.parsed into an object and assigned to a variable (data here). After filtering, you'd have to JSON.stringify it before putting it back to localStorage. Also, this requires numeric IDs, it is not a general solution.