0

I'm trying to remove duplicates objects present in array. here is my object look like my object contain following properties:

function cell(cell_id,x,y){
 this.cell_id = cell_id;
 this.x = x;
 this.y = y;
 }
var cellArray = new Array();

which will contain "cell objects" data, and here are my cell's information

{cell_id:'a',x:250,y:45} -
{cell_id:'b',x:145,y:256}
{cell_id:'a',x:123,y:356}

like that even though the values of x and y differs but I still thinks cell number 3 is a duplicate of cell number 1. I checked following qn's but they didn't helped for me Removing duplicate objects Remove Duplicates from JavaScript Array Thanks in advance.

Community
  • 1
  • 1
BeingNerd
  • 115
  • 2
  • 5
  • 12

2 Answers2

1

You can use something like this:

function removeDupIds(array) {
    var list = {}, id;
    for (var i = 0; i < array.length; i++) {
        id = array[i].cell_id;
        if (id in list) {
            // found a dup id, remove it
            array.splice(i, 1);
            // correct for loop index so it will process the item
            // that just moved down in place of the one we just removed
            --i;
        } else {
            // add the id to our map
            list[id] = true;
        }
    }
}

This uses a temporary map of ids to keep track of which ids have already been encountered in the array. When it finds an id that is already in the map, it removes that element from the array and decrements the for loop index so that it will process the next element that just dropped down in the array in place of the one we just removed.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

You can maintain a separate array that would hold all the different cell_ids, and then filter the cellArray to get your result

cellArray.filter(function (e, i) {
    if (i===0) {
        unique = []; //you'll have to control the scope of this variable. It's global right now
    }
    if (unique.indexOf(e.cell_id) === -1) {
        unique.push(e.cell_id);
        return e;
    }
});

In this solution if two or more instances, with the same cell_id, of your cell class exist inside the cellArray the one with the lower index(in other words, the one that comes first while looping through the array) would be kept, and any subsequent instances would be ignored. The code would have to be modified if you want to apply some other condition.

tewathia
  • 6,890
  • 3
  • 22
  • 27