2

I have a array with objects like this:

{
  __v: 0,
  _id: "5835ced6ffb2476119a597b9",
  castvote: 1,
  time: "2016-11-23T17:16:06.676Z",
  userid: "57e0fa234f243f0710043f8f"
}

How can I make a new array that would filter them by the castvote - like an array containing the objects where castvote is 1, and one where castvote is 2?

3 Answers 3

3

You can do this in controller using $filter,

$scope.castvoteOne = $filter('filter')($scope.results, {castvote: 1});
$scope.castvoteTwo = $filter('filter')($scope.results, {castvote: 2});

DEMO

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

Comments

1

You can use Array.prototype.reduce and a hash table to group the array into an object with key as the castvote and value as the elements that have that particular castvote.

Now you can use result[castvote] to get the result for that particular castvote

See demo below:

var array=[{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:1,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"},{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:2,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"},{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:1,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"}]

var result = array.reduce(function(hash){
  return function(p,c) {
    if(!hash[c.castvote]) {
      hash[c.castvote] = [];
      p[c.castvote] = hash[c.castvote];
    }
    hash[c.castvote].push(c);
    return p;
  };
}(Object.create(null)),{});

// use result[castvote] to get the result for that castvote
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Comments

0

As suggested here

You can use Underscore's groupby to do this generically by the type you want.

_.groupBy($scope.results, "castvote")

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.