Search code examples
javascriptduplicate-detection

Find and show duplicated value


Any idea how to get this:

var MyArr = [0,1,2,3,"something",44,661,3,1,"something"]
var Results = [1,3,"something"]

I just want to find duplicated values in my array.


Solution

  • Use a for loop:

    var Results = [];
    MyArr.forEach(function(el, idx){
        //check if value is duplicated
        var duplicated = MyArr.indexOf(el, idx + 1) > 0;
        if(duplicated && Results.indexOf(el) < 0) {
            //duplicated and not in array
            Results.push(el);
        }
    });