0

I'm writing a javascript code, where the user should be able to search through dimension elements, which is displayed within a "pop-up" window with a table.

The code that displays the elements in the array looks like this:

$element.find("#myInput").on("qv-activate", function (){
    let elemList = [];

    self.backendApi.getData(requestList).then(function (dataPages) {
        let elem = dataPages[0].qMatrix;

        for(let i = 0; i < elem.length; i++){
            elemList.push(elem[i][0].qText);
        }


        $(document).ready(function () {
            $("#myInput").on("keyup", function () {
                var value = $(this).val().toLowerCase();

                for (var i=0; i<elemList.length; i++) {
                    if (elemList[i].toLowerCase().indexOf(value) >= 0){

                        $element.find('#searchTable').prepend('<tr><td id="searchElem">' + elemList[i] + '</td></tr>');
                    }
                }
            });
        });
    })
})

The only problem is, when I use the searchbar, it presents the element multiple times. Is there a way I can make sure, that the .prepend() only prepends if it is not the same value as before? Some kind of; if element value is identical with the before prepended value, then don't prepend?

Hope it makes sense, and you have a solution to my problem. Thanks!

Rasmus Hye
  • 33
  • 6

1 Answers1

0

Instead of calling prepend in the second for loop, make a new array and append elemList[i] to that.

Then use a solution from "Get all unique values in an array (remove duplicates)" to remove the duplicates from the array. For example, if values is your new array:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}
values = values.filter(onlyUnique);

Finally, loop through your new array and call prepend on each.

APerson
  • 8,140
  • 8
  • 35
  • 49