0

I need to remove empty values from Java script array data. Here I am using this code to get data from select box options. Please help me how to avoid empty elements before sending to server.

Javascript Code

var attributevalues = new Array();
        $('select[name=attributevalue]').each(function(){
           attributevalues.push($(this).val());
        });
aurelius
  • 3,946
  • 7
  • 40
  • 73
jack brone
  • 205
  • 5
  • 24
  • 4
    possible duplicate of [Remove empty elements from an array in Javascript](http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript) – Script47 Aug 21 '15 at 11:54
  • @Script47 can you tell me how to implement that for my code. I am new to javascript – jack brone Aug 21 '15 at 11:57
  • 1
    check first if the value is not empty `var attributevalues = []; $('select[name=attributevalue]').each(function () { if ($(this).val().length) attributevalues.push($(this).val()); });` – Tushar Aug 21 '15 at 11:59

3 Answers3

3

Check for that before pushing, like this:

var attributevalues = new Array();

$('select[name=attributevalue]').each(function() {
    if ($(this).val())
        attributevalues.push($(this).val());
});
AhmadAssaf
  • 3,556
  • 5
  • 31
  • 42
0

Other shortcut method available with jQuery is grep. Using that code will be like below -

attributevalues = $.grep(attributevalues,function(value){ return value });

give it a try

Vishnu Atrai
  • 2,370
  • 22
  • 24
0
var trim = function ( ary ) { // remove empty elements
    return ary.filter(function (item) {
        return !!item;
    });
};
Shilly
  • 8,511
  • 1
  • 18
  • 24