1

I am trying to write a jquery $.each() function that takes in an array and puts the duplicates from that array into another array. I know how to do it using a for loop as seen below, but can't seem to figure it out in an $.each function. Any help would be appreciated. Thanks.

$.duplicates = function(arr) {
    dup = [];
    for (var i = 0; i < arr.length; i++){
        for (var j = i + 1; j < arr.length; j++){
            if (arr[i] === arr[j]){
                dup.push(arr[i]);
            }
        }
    }
    return dup;
};
Sxkaur
  • 235
  • 2
  • 10

1 Answers1

0

Try this

$.duplicates = function (arr) {
    dup = []
    $.each(arr, function (i, val1) {
        $.each(arr, function (j, val2) {
            if (val1 === val2 && i !== j) {
                if ($.inArray(val1, dup) === -1) dup.push(val1);
            }
        });
    });
    return dup;
};

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • Thanks for the suggestion, but I was hoping to convert this to an $.each() loop without the use of for loops, since I'm working on a Jquery project and would like to maintain consistency. – Sxkaur Jun 10 '13 at 20:56
  • Glad to have helped.. This is not completely refactored :) – Sushanth -- Jun 10 '13 at 21:27
  • Except the fiddle example didn't work. You have it called as dups(arr). Shouldn't it be $.duplicates(arr) to actually apply the fraction on array. Nonetheless, changing that worked for me. Thank you very much. – Sxkaur Jun 10 '13 at 21:32
  • That was a typo I guess :) – Sushanth -- Jun 10 '13 at 21:32