3

I have this array of objects

var list = [{
    "questionId": 1,
    "correctChoiceIds": [],
    "choiceId": 0,
    "number": 1
}, {
    "questionId": 1,
    "correctChoiceIds": [1234, 4567],
    "choiceId": 0,
    "number": 2,
}, {
    "questionId": 2,
    "correctChoiceIds": [],
    "choiceId": 0,
    "number": 3
}];

//This filter gives me an array with list[0] and list[1]
var filterQuestion = $filter('filter')(list, { questionId: 1 }, true);

I want to filter all those with an empty array for their correctChoiceIds.

var filterNoCorrectChoice= $filter('filter')(list, { correctChoiceIds: [] }, true);

This is what I came up with but it simply gives me nothing. I'm not sure if this is the right way or why it results to nothing.

3 Answers 3

2

see demo

Use the filter like this,

  var filterNoCorrectChoice= $filter('filter')(list,function(item) {
        // must have array, and array must be empty
        return item.correctChoiceIds && item.correctChoiceIds.length === 0;
    });
Sign up to request clarification or add additional context in comments.

Comments

0

method filter native

var filterQuestion = list.filter(function(el){ return el.correctChoiceIds.length<1; });
// result
console.log(filterQuestion);

Comments

0

I want to filter all those with an empty array for their correctChoiceIds

You don't need an angular filter for that, use a standard, native javascript filter...

list.filter(x => !x.correctChoiceIds.length);

2 Comments

This one also works but I don't understand quite understand the syntax. I am still a beginner.
@riyu you can have a look at the docs for filter and for arrow functions as well, but basically you are filtering all the items in your list which have an empty correctChoiceIds array (x.correctChoiceIds.length === 0, 0 is a falsy value in javascript, that's why I negate the condition with the !). Hope now it is more clear ;)

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.