jQuery Data Type How to - Remove empty strings from array while keeping record of indexes with non empty strings








Question

We would like to know how to remove empty strings from array while keeping record of indexes with non empty strings.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from   w w  w. j a  v  a 2  s .c  o  m-->
var myArray = ["I", "am", "", "still", "here", "", "man"] ;
var myNewArray = [] ;
var myOldPosition = [] ;
for(var i=0, max = myArray.length ; i < max ; i++){
    myArray[i] == '' ? true : myNewArray.push(myArray[i]) 
    myArray[i] == '' ? true : myOldPosition.push(i)    
}
document.writeln(myNewArray) ;
document.writeln(myOldPosition);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: