flashpunk
flashpunk

Reputation: 772

Javascript remove remove key with false value

I'm trying to modify an array before submitting it to an api that requires only the id's. I've generated a an array of values, however, my array contains false values depending on how the user interacts with the UI.

    [2: true, 3: true, 5: true]

However, sometimes it displays like this:

    [1: false, 2: true, 3: true, 5: true, 6: false]

How can I filter this so that it removes the false values, and also removes the values, so the ideal data would look like this:

    [2, 3, 5] 

Upvotes: 0

Views: 1673

Answers (3)

Tibos
Tibos

Reputation: 27823

It's not very clear what the shape of your input is because what you wrote is not valid JS syntax.

Assuming that your initial "array" is in fact a map (object), you can do this:

var initial =  {1: false, 2: true, 3: true, 5: true, 6: false};
var final = []; // the array that will contain the result
for (var key in initial) { // iterate through all properties
  if (initial.hasOwnProperty(key)){ // safety check against object poisoning
    if (initial[key]) { // only push true values
      final.push(+key); // + converts the key to a number. Remove it if you want string
    }
  }
}

console.log(final); // [2,3,5]

Upvotes: 1

Atle
Atle

Reputation: 1877

You can create a new array and loop the old one like this and add the values which are true to the new array.

var old_array = [false, true, true, true, false];
var new_array = new Array();
for(i = 0; i < old_array.length; i++) {
    if (old_array[i] == true) {
        new_array.push(old_array[i]);
    }
}

Upvotes: 0

Akshay Khandelwal
Akshay Khandelwal

Reputation: 1570

So say

The

var arr = [false, true, false, true, true];

The function to remove the values

 function removeFalseValues(array){
    for(var i = 0 ; i < array.length; i++){
         if(array[i] == false){
              delete(array[i]);
         }
    }
    return array;
}

And the call

removeFalseValues(arr);

Upvotes: 0

Related Questions