0

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

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

What your map returns as follows

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

because it first check wheather the item.x is truthy or not. As it true always so it returns the value after &&

and when you apply the set, It will filter the unique value from the array

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

Alternate apprach

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

const strArray = myArray.map(({ x, y }) => `${x}/${y}`);
const str = [...new Set(strArray)];
const result = str.map((str) => {
  const [x, y] = str.split("/");
  return { x, y };
});

console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.