Skip to content
Advertisement

How to filter undefined values from Array JavaScript?

The code below is working fine it’s filtering duplicate values from Array but it’s not filtering undefined Values console.log([67, undefined]). i want to filter undefined values and duplicate values from array and output in options values as selected. I would be grateful for any help.

i have two datatable with drag and drop functionality. each row of datatable contain the IDs. when i drag the row of table 1 into table 2. the data stored into the Array. i have the addArray function for push the IDs into an Array there also filtering the duplicate IDs and make it uniqueArray. now i want to create the Select option Element which containing the iDs as a value. I want if i drag out a value from Array then the select options update automatically and delete the option from it…?

js

$(document).ready(function () {
    new Sortable(drag, {
        group: 'sortables',
        multiDrag: true, // Enable multi-drag
        selectedClass: 'selected', // The class applied to the selected items
        fallbackTolerance: 3, // So that we can select items on mobile
        animation: 150,
        onUpdate: function (e, tr) {
            addArray();
            checkFields();
        },
    });

    new Sortable(drop, {
        group: "sortables",
        multiDrag: true, // Enable multi-drag
        selectedClass: 'selected', // The class applied to the selected items
        fallbackTolerance: 3, // So that we can select items on mobile
        animation: 150,
        onChange: function (event, tr) {
            Sorting();
            addArray();
            checkFields();
        },
    });


    function addArray() {
        let uniqueArray = [],
            html = [];
        $('#drop').children().each(function () {
            const pk = $(this).data('pk');
            if (pk && !uniqueArray.includes(pk)) {
                uniqueArray.push(pk);
                html.push(`<option value="${pk}">${pk}</option>`);
            }
        });
        $('#id_articles').html(html.join(""))
    }


    function Sorting() {
        sort = [];
        $('#drop').children().each(function () {
            sort.push({ 'pk': $(this).data('pk'), 'order': $(this).index() })
        });
        let crf_token = $('[name="csrfmiddlewaretoken"]').attr('value') // csrf token
        $.ajax({
            url: "/rundown/sorts/",
            type: "post",
            headers: { "X-CSRFToken": crf_token },
            datatype: 'json',
            data: {
                'sort': JSON.stringify(sort),
            },
            success: function () {
                console.log('success')
            }
        });
    };

    function checkFields() {
        if ($('#drop tr').length >= 1) {
            $('#drop').find('#blank_row').remove();
        } else {
            $('#drop').append($("<tr>").attr("id", "blank_row")
                .append($('<td>').attr("colspan", '4')
                    .text('Drop here...')));
        }
    };
});

Advertisement

Answer

You do not have a filter. Why not just test

function stop_duplicate_in_array(array, value) {
  if (!value && value !== 0) return array; // value is falsy but not 0
  if (!array.includes(value)) array.push(value);
  return array;
}

if 0 is not a possible value, remove && value !== 0

function stop_duplicate_in_array(array, value) {
  if (value && !array.includes(value)) array.push(value);
  return array;
}

You can simplify

function addArray() {
  let uniqueArray = [],
    html = [];
  $('#drop').children().each(function() {
    const pk = $(this).data('pk');
    if (pk && !uniqueArray.includes(pk)) {
      uniqueArray.push(pk);
      html.push(`<option value="${pk}">${pk}</option>`);
    }
  });
  $('#id_articles').html(html.join(""))
}
addArray()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="drop">
  <article data-pk="A">A</article>
  <article>Undefined</article>
  <article data-pk="B">B</article>
  <article data-pk="">Empty</article>
  <article data-pk="C">C</article>
</div>

<select id="id_articles"></select>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement