简体   繁体   中英

Clean undefined items in Numeric Array and sort it by javascript

i have an array created inside for loops

below is an array of numbers contains undefined items & i dont know the right way to remove undefined items and sort it finely , see:

2426,3045,,1680,,,1323,,,,1311

after sorting , here is first two items merged :

24263045,1680,,1323,,,1311,,,,

Here is my code:

var textcontent = 'larg text content larg text content larg text content larg text content larg text content larg text content';
var words = 'content larg text';
var word = words.split(' ');

for(var i=0;i<word.length;i++){
var kx=[];
kx[i] = textcontent.indexOf(word[i]);

function sortNumber(a,b) {
return a - b;
}
//trying to sort that
var vk = kx.sort(sortNumber);
document.write(vk);
// it returns something like this
// 24263045,1680,,1323,,,1311,,,, 
}

How to remove undefined items and sort it to be

1311,1323,1680,2426,3045

You can make use of filter() .

var arr = [2426,3045,,1680,,,1323,,,,1311];
function test(array){
    var arr = array.filter(function(item){
      return item && item!='';//Check if string item is empty.
    })
    console.log(arr);
    return arr;
}
//Call
var arr = test(arr).sort();//To sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM