1

I have the following array filter with a callback function:

array.filter(createPredicateFn(expression, comparator));

My call back function is declared as follow:

function createPredicateFn(expression, comparator) {

How can I get the index of the element inside my createPredicateFn?

Edit:

here is my predicate function:

     function createPredicateFn(expression, comparator) {
            var predicateFn;

            if (comparator === true) {
                comparator = angular.equals;
            } else if (!angular.isFunction(comparator)) {
                comparator = function (actual, expected) {
                    if (angular.isObject(actual) || angular.isObject(expected)) {
                        // Prevent an object to be considered equal to a string like `'[object'`
                        return false;
                    }

                    actual = angular.lowercase('' + actual);
                    expected = angular.lowercase('' + expected);
                    return actual.indexOf(expected) !== -1;
                };
            }

            predicateFn = function (item) {
                return deepCompare(item, expression, comparator);
            };

        }
1
  • We can't help you without the code for your createPredicateFn Commented Dec 5, 2014 at 15:05

1 Answer 1

3

Within your createPredicateFn() you have to return another function. This inner function can have up to three parameters:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

(Source: MDN)

Hence the second parameter of your inner function is the index you look for.

A simplistic example could look like this:

function createPredicateFn(expression, comparator) {
  return function( val, index, arr ) {
    // do something and return a boolean here
    return index % 2 == 0;
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

I tried that and get the index however, I can't make my function working (see my edit)
Your given function never returns a function, but nothing (hence undefined). When you want to use a generator function, that generator has to return a function reference, so filter() knows, what function to use.
I'm a bit lost...Could you please rewrite my function with access to the index? I got this function from angularjs filter and I'm not very comfortable with it, that's why I'm not 100% sure of what I'm doing.
@ncohen The actual function, that determines, whether an entry should stay in the array or get filtered is that predicateFn(), right? If so, just return this at the end of the function.
Got it, I will try that later today! Thanks
|

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.