0

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

2
  • 1
    So "duplicate" here is just estimated by the last value in the arrays? Commented Dec 4, 2014 at 11:14
  • yah last value @Sirko Commented Dec 4, 2014 at 11:16

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Just try with:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.