简体   繁体   中英

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
]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM