0

Lets say i have an array filled with objects like this:

 {conversation_id: 38
  id: 99
  is_seen: 1 
  message: "Hej Kristina"
  timestamp: "2015-07-08T10:50:49.000Z"'
 }

Now I wish I could find out how many of these objects has the value is_seen set to 1 and conversation_id set to 38.

I could solve this by using a forEach loop, however I am looking for a solution that is cleaner and maybe even more efficient.

My application is an AngularJs application, so I'm looking for either native JavaScript or Angular ways to solve this.

1
  • 4
    you could use Array.filter(). Something along the lines of: my_array.filter(function(el) { return el.conversation_id == 38 && is_seen == 1; }).length; Commented Jul 8, 2015 at 13:02

2 Answers 2

3

You can use angular js filter

  var seenObjects = $filter('filter')(itemsList, function(rule) {
     return rule.is_seen === 1 && rule.conversation_id === 38;
   });
console.log(seenObjects.length);
Sign up to request clarification or add additional context in comments.

1 Comment

You forgot to check conversation_id.
2

You can use the native Array.filter() function:

var countOfSeenItems = my_array.filter(function (el) {
  return el.conversation_id == 38 && is_seen == 1; 
}).length;

3 Comments

Array.prototype.filter is not available in Internet Explorer before version 9 - kangax.github.io/compat-table/es5/#Array.prototype.filter
@phuzi what do you suggest for legacy then?
@MarcRasmussen there's a polyfill on MDN - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.