Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all ,

i have a javascript array and it may contains a duplicate variables. now i want to remove all the duplicate variable except the one which push at very last.

for example my array is

var array = {1,2,1,3,4,5,1,6,6,7,6,5,4,2,3};

here one is entered thrice so i want to remove the first two ones and wants to keep the last. same for other integers.


i try array.splice method but it removes all the duplicate values from array.
Posted

Try jQuery, since you want the last duplicate one to stay, I use string.reverse(). Try to understand the logic.
XML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    var array = [1,2,1,3,4,5,1,6,6,7,6,5,4,2,3];
    array.reverse();
     var uniqueArray = [];
    $.each(array, function(key, element){
        if($.inArray(element, uniqueArray ) === -1)
            uniqueArray.push(element);
    });
    uniqueArray.reverse();
    console.log(uniqueArray);
  });
});
</script>
</head>
<body>
<button type="button">Array Slimming!</button>
</body>
</html>

My hands were somehow itchy, so I wrote down the JavaScript code here too:
XML
<!DOCTYPE html>
<html>
<head>
<script>
function slim() {

    var array = [1,2,1,3,4,5,1,6,6,7,6,5,4,2,3];
    array.reverse();
     var uniqueArray = [];

    for (var i=0; i < array.length; i++) {
        var element = array[i];
        if ( uniqueArray.indexOf(element) === -1)
            uniqueArray.push(element);
    };
    uniqueArray.reverse();
    console.log(uniqueArray);

}
</script>
</head>
<body>
<button type="button" onclick="slim()">Array Slimming!</button>
</body>
</html>
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900