Defgun
Defgun

Reputation: 79

How to remove identical objects from an array checking all of the objects values?

I have an array containing hundreds sometimes thousands of objects with vectors of 3D objects. There are three or even more identical objects in the array (I think they are needed also for the render to know which side the normals of the surface are facing) but for what I want to do I need the identical objects gone. The bad part is, I cant just check one value since sometimes two objects share for example the same value for x but then the y or z is different. Is there an efficient way to do that? Unfortunately all tutorials I found deal with checking for one value and I need to check all of them.

const vectors = [
{x: 6.869495194905539e-9, y: -0.11905603855848312, z: -0.3318425416946411},
{x: 6.869495194905539e-9, y: -0.11905603855848312, z: -0.3318425416946411},
{x: 6.869495194905539e-9, y: -0.11905603855848312, z: -0.3318425416946411},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.12705090641975403, y: -0.11905603855848312, z: -0.306582510471344},
{x: 0.12705090641975403, y: -0.11905603855848312, z: -0.306582510471344},
{x: 0.12705090641975403, y: -0.11905603855848312, z: -0.306582510471344},
etc
etc
]

Upvotes: 2

Views: 51

Answers (2)

Defgun
Defgun

Reputation: 79

Nevermind, I did finally find an answer in another thread here.

var result = arr.reduce((unique, o) => {
    if(!unique.some(obj => obj.x === o.x && obj.y === o.y && obj.z === o.z)) {
      unique.push(o);
    }
    return unique;
},[]);
console.log(result);

Remove duplicate values from an array of objects in javascript

Upvotes: 1

Osakr
Osakr

Reputation: 1066

You can use sets to remove the duplicates:

const vectors = [
{x: 6.869495194905539e-9, y: -0.11905603855848312, z: -0.3318425416946411},
{x: 6.869495194905539e-9, y: -0.11905603855848312, z: -0.3318425416946411},
{x: 6.869495194905539e-9, y: -0.11905603855848312, z: -0.3318425416946411},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.06476999074220657, y: -0.11905603855848312, z: -0.3254662752151489},
{x: 0.12705090641975403, y: -0.11905603855848312, z: -0.306582510471344},
{x: 0.12705090641975403, y: -0.11905603855848312, z: -0.306582510471344},
{x: 0.12705090641975403, y: -0.11905603855848312, z: -0.306582510471344}
];

const arrayWithoutDuplicates = Array.from(
  new Set(vectors.map(v => JSON.stringify(v))),
  json => JSON.parse(json)
);

Upvotes: 3

Related Questions