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!
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!
Share Improve this question edited Mar 11, 2015 at 14:29 Kalman 8,1311 gold badge28 silver badges45 bronze badges asked Mar 11, 2015 at 6:50 user1438823user1438823 1,3133 gold badges19 silver badges25 bronze badges 2- Did you tried anything, post it to see the point of issue? – Jai Commented Mar 11, 2015 at 6:55
- 3 have a look at lodash - I use that in both node and ember apps for this sort of thing – user156888 Commented Mar 11, 2015 at 10:52
3 Answers
Reset to default 9We 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)
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
Similar solution using forEach
(& not forgetting to use get
for item.get('property')
):
unique: Em.puted('model', function() {
var uniqueObjects = [];
this.get('model').forEach(function(item) {
if (!uniqueObjects.isAny('property', item.get('property'))) {
uniqueObjects.addObject(item);
}
});
return uniqueObjects;
})