Amol Birajdar
Amol Birajdar

Reputation: 63

How to remove duplicate from object list in javasccript

 $(".search").keyup(function(){
     var val = this.value;

        $.ajax({
        type: "POST",
        url:  "search?entered=" + val,
        beforeSend: function(){    
            $(".search").css("background","#FFF");
        },
        success: function(data){
            for (var i = 0; i < data.length; i++) {
                $(".suggesstions").append("<ul>"+data[i]["category"]+" "+data[i]["productTitle"]+"</ul>");
             }

        }

        });

    });

Here is my code, I want to remove duplicate entries from list and append to.

Upvotes: 1

Views: 91

Answers (5)

let myArray = [2, 5, 5, 7, 7, 8, 9, 9, 9, 1, 3, 3, 4, 5];
     let arrayOutput = [];
                myArray?.map((c) => {
                    (!(arrayOutput.indexOf(c) > -1)) ? arrayOutput.push(c) : null;                
                });
    console.log(arrayOutput)

Upvotes: 0

let myArray = [2, 5, 5, 7, 7, 8, 9, 9, 9, 1, 3, 3, 4, 5];
 let arrayOutput = [];
            myArray?.map((c) => {
                if (!arrayOutput.includes(c)) {
                    arrayOutput.push(c);
                }
            });
console.log(arrayOutput)

Upvotes: 0

zawhtut
zawhtut

Reputation: 8561

One Liner

var arrOutput = Array.from(new Set([1,2,3,4,5,5,6,7,8,9,6,7]));
alert(arrOutput);

Upvotes: 0

Dil85
Dil85

Reputation: 176

I modified the code with remove duplicate value based on productTitle.

 success: function(data){
             var array = [],
             Finalresult = [];

           $.each(data, function (index, value) {
               if ($.inArray(value.productTitle, array) == -1) {
                array.push(value.productTitle);
                Finalresult.push(value);
              }
           });
         for (var i = 0; i < Finalresult.length; i++) {
                        $(".suggesstions").append("<ul>"+Finalresult[i]["category"]+" "+Finalresult[i]["productTitle"]+"</ul>");
                     }
        console.log(Finalresult);

    }

Upvotes: 1

rejo
rejo

Reputation: 3350

First, you have to remove all duplicate entries from array , like this

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

for (var i = 0; i < newArr.length; i++) {
         //your code
}

Upvotes: 1

Related Questions