anonymouselephant
anonymouselephant

Reputation: 43

Can't split commas out of list

I've got a similar list: list = [',99', ',48', ',48', ',44', ',80', ',82', ',88', ',90', '1,1']

I just want the number to the right of the comma, but when I try splitting:

newList = list.split(',')

I get:

AttributeError: 'list' object has no attribute 'split'

Upvotes: 0

Views: 29

Answers (1)

sssurii
sssurii

Reputation: 830

here split will not work because javascript method .split() is to convert string into array and but here list is an object. you can try console.log(typeof variable); to check type of any variable. So here you can simply use jquery function .each() most common function used for traversing an javascript object.

Try below solution:

var list = [',99', ',48', ',48', ',44', ',80', ',82', ',88', ',90', '1,1'];
var new_list = [];
$(list).each(function( index, item ) {
    var item_array = item.split(',');
    $(item_array).each(function( i, num ) {
        if(num && num != '' && typeof num != 'undefined'){
            new_list.push(num);
        }
    });
});

then use new_list instead of list as it will contain desired output:

["99", "48", "48", "44", "80", "82", "88", "90", "1", "1"]

OR can try alternate way:

var list = [',99', ',48', ',48', ',44', ',80', ',82', ',88', ',90', '1,1'];
var list_str = list.toString();
list = list_str.split(',');
list = list.filter(function(item){
          if(!!item){
            return item;
          }
        });

Upvotes: 1

Related Questions