0

Suppose I have an array structured like this:

{ q1: true, q2: false, q3: false, q4: true, q5:true }

Is there a way to remove all the elements that has "false" for a value in AngularJS?

I tried using splice() by getting the index number, with no luck. Now I'm looking for a way where I don't have to use a specific index number.

Any help would be appreciated. Thank you.

3 Answers 3

1

Simple JavaScript approach

var r = {
  q1: true,
  q2: false,
  q3: false,
  q4: true,
  q5: true
};

for (a in r) {
  if (!r[a]) {
    delete r[a]
  }
}

console.log(r);

Sign up to request clarification or add additional context in comments.

1 Comment

Just what I was looking for. Thank you. It works great. :)
0

This is not an array, this is an object. You can use this function to remove every key whose value is falsy with:

angular.forEach(obj, function (val, key) {
  if (!val) {
    delete obj[key];
  }
});

Comments

0

You supplied an object, not an array. Array.prototype.splice works with arrays, not objects.

To filter out unwanted values from an array, you should use Array.prototype.filter.

[true, false, false, true, true].filter(function(el){ return el; });
// returns [true, true, true]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.