SkillsIndexOutOfBounds
SkillsIndexOutOfBounds

Reputation: 539

javascript remove duplicates from array of arrays

How to remove duplicates on an array like below:

arr = [
    [828, 187, 1, 14, 1, 25, 1417608935730],
    [828, 187, 1, 14, 1, 25, 1417608935740],
    [828, 187, 1, 14, 1, 25, 1417608935750],
    [828, 187, 1, 14, 1, 25, 1417608935760],
    [600, 578, 1, 14, 1, 25, 1417608935760],
    [828, 187, 1, 14, 1, 25, 1417608935780],
    [828, 187, 1, 14, 1, 25, 1417608935790]
]

Since 4th and 5th array have 1417608935760 similar value I want to delete next duplicate and keep only one.

I tried this but not working:

$.each(arr, function(i, insidearr){  
    if($.inArray(insidearr[6], uniqueNames) === -1) 
        uniqueNames.push(insidearr);
});

Pls help. Thanks in advance

Upvotes: 0

Views: 509

Answers (3)

Leo
Leo

Reputation: 13828

try this one:

var arr = [
    [828, 187, 1, 14, 1, 25, 1417608935730],
    [828, 187, 1, 14, 1, 25, 1417608935740],
    [828, 187, 1, 14, 1, 25, 1417608935750],
    [828, 187, 1, 14, 1, 25, 1417608935760],
    [600, 578, 1, 14, 1, 25, 1417608935760],
    [828, 187, 1, 14, 1, 25, 1417608935780],
    [828, 187, 1, 14, 1, 25, 1417608935790]
];

var len = arr.length;
while(--len) {
  if(arr[len][6] == arr[len-1][6]) {
    arr.splice(len-1, 1)
  }
}
console.log(arr); // here is what you want

If you don't want to manipulate arr, you just need to clone the array by var newArr = arr.slice()

Upvotes: 0

hsz
hsz

Reputation: 152206

Just try with:

var uniqueArr = $.grep(arr, function(insidearr){  
    if ($.inArray(insidearr[6], uniqueNames) === -1) {
        uniqueNames.push(insidearr[6]);
        return true;
    }
});

Upvotes: 0

Barmar
Barmar

Reputation: 780724

You're pushing the entire row into uniqueNames. The array will never be equal to the number at the end of each row, so the $.inArray() test will always fail. You need separate arrays for just the element you're comparing and the resulting array.

var newArray = [];
var uniqueNames = {};
$.each(arr, function(i, insidearr) {
    if (!(insidearr[6] in uniqueNames)) {
        newArray.push(insidearr);
        uniqueNames[insidearr[6]] = true;
    }
});

I used an object rather than an array for uniqueNames, because searching for an object key is faster than scanning an array.

Upvotes: 2

Related Questions