0

I'm sure I'm missing something obvious but the below code does not work when the currentRecord found is true.

What is the best way to iterate through an array and when a match is found, return that record? I think forEach here is part AngularJS.

function getCurrentRecord() {

    homePageVideos.forEach(function(rec) {
        if (rec.currentRecord === true){
            return rec;
        }
    });

}
3
  • Looks correct, can you provide us with some more context Commented May 12, 2015 at 19:00
  • Do you want to return all matches or just the first match? Looking at the code, it appears you only want the the first. Commented May 12, 2015 at 19:31
  • Yes. First (and only in my case). Should my code work as is? It seems not to when I debug in chrome Commented May 12, 2015 at 20:02

3 Answers 3

2

From MDN documentation of Array.prototype.forEach:

Note: There is no way to stop or break a forEach() loop. The solution is to use Array.prototype.every() or Array.prototype.some(). See example below.

Same goes for angular.forEach.

But if you were to use a simple for-loop, you could do it like so:

for (var i=0; i < homePageVideos.length; i++){
  var rec = homePageVideos[i];
  if (rec.currentRecord === true){
    return rec;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's an interesting question and this certainly seems like the best answer. The MDN reference also includes a polyfill should one need it.
0

You could simply use angular filter. Inside controller you could accomplish this by using $filter inside controller

function getCurrentRecord() {
    var result = $filter('filter')(homePageVideos, true, true); //strict checking
    return result.length > 0? result[0]: [];
}

Comments

0

JavaScript provides several array iteration functions. I would use filter() but the solution would depend on the browser compatibility you require (IE9+, FF1.5+).

function getCurrentRecord() {
  return homePageVideos.filter(function(rec) {
    return rec.currentRecord
  });
}

1 Comment

Why not offer a better solution? The question asked what is the best way to iterate and return a match.

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.