user1438823
user1438823

Reputation: 1313

Ember JS how to get an array with unique property values

I have a array with objects which has different properties. There are objects with similar properties. For example,

var array=[{'property':1},{'property':2},{'property':1}]

How to get the array with unique properties using ember js?

Finally I need an array of

[{'property':1},{'property':2}]

your kind help is really appreciated.

Update: I tried the uniq() method. But that does not allow to pass the property as ember allows with sorting.

Thank You!

Upvotes: 4

Views: 6006

Answers (3)

siwalikm
siwalikm

Reputation: 1875

We can do it in just one line of code using Ember's uniqBy method.

Suppose we have this array =>

var arrayName=[{'property':1},{'property':2},{'property':1}]

To get an unique array, you need to do the following =>

arrayName.uniqBy('property');

Which will return the following =>

var arrayName=[{'property':1},{'property':2}]

uniqBy returns a new enumerable that contains only items containing a unique property value. The default implementation returns an array regardless of the receiver type.(link to Ember Guide)

Upvotes: 9

gerry3
gerry3

Reputation: 21460

Similar solution using forEach (& not forgetting to use get for item.get('property')):

unique: Em.computed('model', function() {
  var uniqueObjects = [];
  this.get('model').forEach(function(item) {
    if (!uniqueObjects.isAny('property', item.get('property'))) {
      uniqueObjects.addObject(item);
    }
  });
  return uniqueObjects;
})

Upvotes: 2

Kalman
Kalman

Reputation: 8131

One way to do this is to use the filter method in conjunction with isAny method

App.IndexController = Ember.ArrayController.extend({

  unique: function(){
    var model = this.get('model');
    var uniqueObjects = [];

    return model.filter(function(item){
      if(!uniqueObjects.isAny('property', item.property)){
        uniqueObjects.push(item);

        return true;
      }

      return false;
    });
  }.property('model')
});

Working example here

Upvotes: 4

Related Questions