3

I am new to node JavaScript and do not understand the syntax too much. My code

console.log(index+ "\t" + output[index]);

Outputs empty strings in my array.

So I have created a new method

var array = removingEmptyString(output[index]);
function removingEmptyString(array)
{
    var newArray = [];

    for(var i in array)
        {
            if(i != "" || i != null || i != " ")
                {
                    newArray[i] = i;
                }
        }

    }

What I do not understand is if I declared my arrays correct? Also if I passed int he array into the removingEmptyString correctly, also if declaring the new array and inserting the non empty string into that array are correct?

3
  • 2
    You're never returning anything? i will be the key, not the value.
    – h2ooooooo
    Commented Nov 29, 2013 at 17:01
  • look here: stackoverflow.com/questions/281264/… Commented Nov 29, 2013 at 17:02
  • also, in js, arrays are not continuous. the way you do things, you'll have gaps instead of your empty values.
    – njzk2
    Commented Nov 29, 2013 at 17:02

2 Answers 2

2

One problem is that Arrays and Objects are slightly different things. To iterate over an array you can use things like:

for (var i=0; i<arr.length; i++) {
  /* code */
}

arr.forEach(function(item, index, arr) {
  /* code */
});

The for..in structure is used to iterate over the keys in an Object:

var obj = { b : 1, c:2 }

for (var key in obj) {
  console.log(key) // will output first b then c
}

The simplest way to remove empty values in an array is this:

var arr = [ 1, '', null, 3, 0, undefined, '', 4 ];
var filtered = arr.filter(function(item){ return item != null && item !== ''; });

console.log(filtered) // [1,3,0,4]

Obviously you can add more things that should be filtered out of your original array by changing the function passed to filter.

4
  • where it says arr would i put in output[index] or just output Commented Nov 29, 2013 at 17:08
  • You put your array there. From the looks of it, it is output[index], but i can't be sure.
    – Tibos
    Commented Nov 29, 2013 at 17:10
  • it did not work i still got an output of tree,,, Commented Nov 29, 2013 at 17:11
  • What are the contents of the original array?
    – Tibos
    Commented Nov 29, 2013 at 17:22
0

Or a simple method using the filter method.

var newArray = oldArray.filter(function(v){return v!==''});
1
  • where it says oldArray would i put in output[index] or just output Commented Nov 29, 2013 at 17:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.