How to store separately the repeated values inside array of objects

Viewed 72

I have this array of objects in Javascript:

var arrayData = [
            { id: "0", x: -1, y: 38},
            { id: "1", x: -2.7823, y: 43.444},
            { id: "2", x: -1.1654, y: 38.12088},
            { id: "3", x: -1, y: 38},
            { id: "4", x: -2.7823, y: 43.444 },
            { id: "5", x: -1.1654, y: 38.12088},
            { id: "6", x: -1.1654, y: 38.12088},
            
        ]

and i'd need to check what objects have the same property x and y and someway store this objects separately so i can access later to them. i've got this:


var copy = arrayData.slice(0);
// first loop goes over every element
               for (var i = 0; i < arrayData.length; i ++) {  
                    
                   // loop over every element in the copy and see if it's the same
                   for (var w = i + 1; w < copy.length; w++) {
                       if ((arrayFotos[i].x === copy[w].x) && (arrayFotos[i].y === copy[w].y)) {                               
                           
                           if(!duplicates.includes(arrayFotos[i].id))
                               duplicates.push(arrayFotos[i].id);
                           if(!duplicates.includes(copy[w].id))
                               duplicates.push(copy[w].id);
                       }                          
                                           
                   }
      
   

This returns me an array with all ids of the objects which have repeated x and y properties but i need a way to store them separately so i have: [0,3][1,4][2,5,6]. Is there any way to do it? Thanks if u want to help me.

1 Answers

You could take a hash table and collect id for same coordinates.

var arrayData = [{ id: "0", x: -1, y: 38 }, { id: "1", x: -2.7823, y: 43.444 },  { id: "2", x: -1.1654, y: 38.12088 }, { id: "3", x: -1, y: 38 }, { id: "4", x: -2.7823, y: 43.444 }, { id: "5", x: -1.1654, y: 38.12088 }, { id: "6", x: -1.1654, y: 38.12088 }],
    duplicates
    hashtable = {};

for (var i = 0; i < arrayData.length; i++) {  
    let key = ['x', 'y'].map(k => arrayData[i][k]).join('|');
    hashtable[key] = hashtable[key] || [];
    hashtable[key].push(arrayData[i].id);
}

duplicates = Object.values(hashtable);

console.log(duplicates);

Related