Search code examples
javascriptarraysobjectdistinct

how to fetch distinct objects in array : Javascript


I am trying to fetch unique objects from an array which may have duplicate objects. I have tried new Set and new Map but i still haven't gotten my result.

For example i have the following array of objects

const myArray = [{ x: 10, y: 22}, {  x: 11,  y: 22}, {  x: 12,  y: 22}, {  x: 12,  y: 22}, {  x: 12,  y: 23}];

console.log([...new Set(myArray.map((item) => item.x && item.y ))]) // [22, 23]

when i want this

[{ x: 10, y: 22}, {  x: 11,  y: 22}, {  x: 12,  y: 22}, {  x: 12,  y: 23}];

it should remove the fourth object in myArray, since it is repeating


Solution

  • You can use reduce for that along with some:

    const myArray = [{ x: 10, y: 22}, {  x: 11,  y: 22}, {  x: 12,  y: 22}, {  x: 12,  y: 22}, {  x: 12,  y: 23}];
    
    const Filtered = [];
    
    const filterDuplicates = myArray.reduce((arr, el) => {
        if(!arr.some(current => current.x === el.x && current.y === el.y)) {
           arr.push(el);
        }
        return arr;
    }, Filtered);
    
    console.log(Filtered);