specify more than one clause underscore.js

I'm using underscore.js to filter a JSON array. I could not find a way to combine more than one clause in a _.where method. (ps: I'm filtering a string property)

Is it possible?

Answers:

Answer

As described in the comments to your question, it looks like you're trying to filter an array with an OR operation - which is not possible using _.where.

Use _.filter instead:

var arr = [{ x:1, y:2 }, { x:2, y:1 }, { x:3, y:3 }];
var result = _.filter(arr, function(obj) {
     // return true for every valid entry!
     return obj.x == 1 || obj.y == 1;
});
console.log(result); // [{ x:1, y:2 },{ x:2, y:1 }]

Fiddle

Answer

Its not clear, what exactly trying to do. But this is a functional version of what you are trying to do. You can define as many functions as you want, in the functionsArray, which will accept a single word.

var words = ["school", "cry", "google", "fly"];

function has(chr) {
    return function(word) {
        return _.contains(word, chr);
    };
};

var functionsArray = [has("o"), has("f")];

console.log(_.filter(words, function(word) {
    return _.some(functionsArray, function(currentFunction) {
        return currentFunction(word);
    });
}));

Output

[ 'school', 'google', 'fly' ]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.