Remove duplicate values from array in jQuery

$.unique(array)

The unique() function remove duplicate values from array in jQuery. That meanse it returns an array of the unique elements in the original array. The below code return unique and sorted array.

var myArr = [2, 5, 5, 7, 7, 8, 9, 9, 9, 1, 3, 3, 4, 5];
var newArr = $.unique(myArr.sort()).sort();

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('#btnClick').click(function () {
        var myArr = [2, 5, 5, 7, 7, 8, 9, 9, 9, 1, 3, 3, 4, 5];
        var newArr = $.unique(myArr.sort()).sort();
        var result = "";
        for (var i = 0; i < newArr.length; i++) {
          result += newArr[i] + ",";
        }
        result = result.slice(0, -1) //remove last comma
        alert(result);
      });
    });
  </script>
</head>
<body>
  <div>
    <input type="button" id="btnClick" value="Click" class="Button" />
  </div>
</body>
</html>
DISPLAY

5 comments :

  1. take dis arry [2, 5, 5, 7, 7, 8 ,9 ,9,9,1,3,3,4,5] same codes not works///

    ReplyDelete
    Replies
    1. Yes there is an issue with jQuery. If the last value of an array matches with any of the value it will not remove the last value. To solve this issue first sort the array and then use unique method. I am also changing my code according to your issue.It will definitely work for you.

      Delete
  2. nice use of this function " $.unique(myArr.sort()).sort(); " very coool...

    ReplyDelete