1

Given the following array of objects:

var files = [{
    name: "test1",
    size: 123
}, {
    name: "test1",
    size: 456
}, {
    name: "test2",
    size: 789
}]

If I wanted a new array without the object with the name "test1" and the size 123 the following makes sense to me:

_.filter(files, function(_file) {
    return _file.name !== "test1" && _file.size !== 123;
});

However; this always removes both items with the name "test1". The following returns the desired results:

_.filter(files, function(_file) {
    return _file.name !== "test1" || _file.size !== 123;
});

How come?

1 Answer 1

1

Your actual condition should have been

return !(_file.name === "test1" && _file.size === 123);

because you have to reject items only if both the properties match the specific values, not when any of the properties do not match the specific values.

In your code, for the second element, _file.name !== "test1" is actually false and the entire expression becomes false, so the second item is also skipped.

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

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.