How to remove duplicate data from object in JavaScript

There are multiple ways to remove duplicates from an object in JavaScript

Using Set

Use the Set object which stores unique values of any type.

const students: stirng[] = ['Larry', 'David', 'Mike', 'James', 'London', 'David', 'James'];

const uniqueStudents = [...new Set(students)];

If we console.log(uniqueStudents) we will see that we do not have any duplicate values.

Image

Using Set with Array of Objects

const arr = [
  { name: 'Larry' },
  { name: 'David' },
  { name: 'Mike' },
  { name: 'James' },
  { name: 'London' },
  { name: 'David' },
  { name: 'James' },
];
const unique = [...new Set(arr.map((item) => JSON.stringify(item)))].map(
  (item) => JSON.parse(item)
);

Using filter()

Use the filter() method to create a new array with only unique values.

const myArray = [1, 2, 3, 4, 5, 5, 5, 5, 5, 6, 7, 8, 9, 10];

const uniqueArray = myArray.filter((value, index, self) => self.indexOf(value) === index);

console.log(uniqueArray);

// Will output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using reduce()

Use the reduce() method to create a new array with only unique values.

const myArray = [1, 2, 3, 4, 5, 5, 5, 5, 5, 6, 7, 8, 9, 10]; 

const uniqueArray = myArray.reduce((acc, currentValue) => { if (!acc.includes(currentValue)) { acc.push(currentValue); } return acc; }, []); 

console.log(uniqueArray); 

// Will output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Feel free to reach out if you have any questions or comments.