Removing duplicates after pushing
If you already have an array containing duplicates, transform the array of objects into an array of strings, and then use the Set()
function to eliminate duplicates:
// Declaring an array of objects containing duplicate objects
let arrayOfObjects = [{name: "tom", text: "tasty"}, {name: "tom", text: "tasty"}];
// Transforming array of objects into array of strings
let arrayOfStrings = arrayOfObjects.map(obj => JSON.stringify(obj));
// Creating a new set, Set() returns unique values by definition
let uniqueSet = new Set(arrayOfStrings);
// Transforming set into array and reversing strings to objects
let uniqueArrayOfObjects = [...uniqueSet].map(elem => JSON.parse(elem));
console.log(uniqueArrayOfObjects);
// [{name: "tom", text: "tasty"}]
Checking before pushing
If you don't have duplicates so far and you want to check for duplicates before pushing a new element:
// Declaring an array of objects without duplicates
let arrayOfObjects = [{name: "tom", text: "tasty"}];
// Transforming array of objects into array of strings
let arrayOfStrings = arrayOfObjects.map(obj => JSON.stringify(obj));
// Declaring new element as an example
let newElem = {name: "tom", text: "tasty"};
// Stringifying new element
let newElemString = JSON.stringify(newElem);
// At this point, check if the string is duplicated and add it to array
!arrayOfStrings.includes(newElemString) && arrayOfObjects.push(newElem);
console.log(arrayOfObjects);
// [{name: "tom", text: "tasty"}]