sorting,ember.js,has-many,computed-properties , Emberjs advanced sort hasMany association as a computed property


Emberjs advanced sort hasMany association as a computed property

Question:

Tag: sorting,ember.js,has-many,computed-properties

I have asked a variant of this question here. But basically I need to create a computed property that operated on a hasMany association. I need to do sorting similar to the javascript sort function; where I can do something like

files = ["File 5", "File 1", "File 3", "File 2"];
files.sort(function(a,b){
  return parseInt(b.split(' ').pop()) - parseInt(a.split(' ').pop())
});

result:

["File 5", "File 3", "File 2", "File 1"]

Here is my jsbin: http://emberjs.jsbin.com/simayexose/edit?html,js,output

Any help would be greatly appreciated.

Note: My jsbin presently is not working correctly (for reasons other then this question). I have posted a question about that here. I just did not want to hold up an answer to this question.

Update 1

Thanks @engma. I implemented the instructions. As a matter of fact, I copied and pasted what was posted. This is the new jsbin. http://emberjs.jsbin.com/roqixemuyi/1/edit?html,js,output

I still do not get anything sorted, though. And even if it did, it still would not have sorted the way I would like it.

I need something like the following: (below are errors that I get when I try to implement this in my code, not from jsbin, since I can not get jsbin to work)

  sortedFiles: function(){
    return this.get('files').sort(function(a,b){
      return parseInt(b.split(' ').pop()) - parseInt(a.split(' ').pop());
    });
  }.property('[email protected]')

When I do this I get the following error:

Uncaught TypeError: this.get(...).sort is not a function

So since this.get('files') returns a promise, I figured I would try this;

  sortedFiles: function(){
    return this.get('files').then(function(files){
      return files.sort(function(a,b){
        return parseInt(b.split(' ').pop()) - parseInt(a.split(' ').pop());
      });
    });
  }.property('[email protected]')

But then I get the following error:

Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed {_id: 243, _label: undefined, _state: undefined, _result: undefined, _subscribers: }

BTW, I am using emberjs v1.11.0

And, the sortBy I am using is ember-cli/node_modules/bower-config/node_modules/mout/array/sortBy.js

Here is the code for it

var sort = require('./sort');
var makeIterator = require('../function/makeIterator_');

    /*
     * Sort array by the result of the callback
     */
    function sortBy(arr, callback, context){
        callback = makeIterator(callback, context);

        return sort(arr, function(a, b) {
            a = callback(a);
            b = callback(b);
            return (a < b) ? -1 : ((a > b) ? 1 : 0);
        });
    }

    module.exports = sortBy;

Update 2

So to answer the question how to do an Emberjs advanced sort hasMany association as a computed property; I had to change

  this.get('files').sort(function(a,b){
      ...
  });

  return this.get('files').toArray().sort(function(a,b){
    ...
  });

This allowed me to use the javascript sort and return the desired sorted objects.


Answer:

Ok first of all your JSBin had many issues so lets go throw them one by one

1- you did not include any Ember-Data build, so I included 1, this is needed for the fixtures and the models

<script src="http://builds.emberjs.com/tags/v1.0.0-beta.15/ember-data.js"></script>

2- Your Scripts

var App = window.App = Ember.Application.create({
});
//First this is how to register the adapter
App.ApplicationAdapter = DS.FixtureAdapter.extend({});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    //Second with find you pass in the ID so I am using 1
    //if you want to get all folders use findAll()
    return this.store.find('folder',1);
  } 
});

App.IndexController = Ember.Controller.extend({

});


App.Router.map(function() {
});

App.Folder = DS.Model.extend({
  name: DS.attr('string'),
  files:  DS.hasMany('file',{async:true}),
  sortedFiles: function(){
    //Sorty By has no second parameter, if you need more sorting power, do it your self
    return this.get('files').sortBy('name');
  }.property('[email protected]')

});

App.File = DS.Model.extend({
  name: DS.attr('string'),
  folder: DS.belongsTo('folder',{async:true})
});

App.File.FIXTURES = [
  {
    id: 1,
    name: 'File 5',
    folder:1
  },
  {
    id: 2,
    name: 'File 1',
    folder:1
  },
  {
    id: 3,
    name: 'File 3',
    folder:1
  },
  {
    id: 4,
    name: 'File 2',
    folder:2
  },
  {
    id: 5,
    name: 'File 6',
    folder:2
  },
  {
    id: 6,
    name: 'File 4',
    folder:2
  }
];


App.Folder.FIXTURES = [
  { 
    id: 1,
    name: 'Folder 1',
    files:[1,2,3]
  },
  {
    id: 2,
    name: 'Folder 2',
    files:[4,5,6]
  }
];

Your Template:

<div>
   Folders: <br>
  <ul>
   <li>
     Name: {{model.name}} <br>
     Files:
     {{!-- here we access the sorted files property in the model--}}
     {{#each file in model.sortedFiles}}
       {{file.name}} <br/>
     {{/each}}
  </li>
 </ul>
</div>

Related:


sortable list in emberjs


ember.js,ember-data,handlebars.js
i have loaded a list from server into handlebar. when the list order changes, i need to send the sorted order back to the server. to make a list sortable, i have used jquery-ui.js. when i change the list order by dragging and dropping the list, visually the list order...

Sorting vector of Pointers of Custom Class


c++,sorting,c++11,vector
I have vector<FPGA*> current_generation_, which I'd like to sort by FPGA member fitness_ using the sort_members function. Applicable code follows: bool sort_members (FPGA* fpga_first, FPGA* fpga_second) { return (fpga_first->fitness() < fpga_second->fitness()); }; fpga.hpp #include <vector> class FPGA { public: explicit FPGA(int input_gates, int output_gates, int normal_gates); const int fitness(); protected:...

How to properly unbind jQuery window event handler in Ember component


jquery,ember.js
I know that the best practice for binding an event handler to a window event with jQuery is jQuery(window).on('resize', Ember.run.bind(this, this.handleResize)); If you try to unbind the event handler though in willDestroyElement with $(window).off('resize', this.handleResize); this doesn't work because .on() and .off() must be called with the exact same reference...

Sorting jQuery dataTables by class name when there is no type or value


javascript,jquery,sorting,jquery-datatables
I'm using DataTables: https://www.datatables.net/ Heres my HTML: <div class="dataTable_wrapper"> <table class="table table-striped table-bordered table-hover center" id="dataTables-example"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Actions</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>title 1</td> <td><a href="./action-1"><span class="on"></span></a></td> </tr> <tr>...

Custom API calls with Ember Data


ember.js,ember-data,ember-cli
I don't know if this is possible with Ember data, although I am kind of doubtful, but the API I am working with supports being able to produce 'or' queries by hitting URLs like, /v1/subjects?first_name||last_name=*dr* this would result in a query that looks like select * from subjects where first_name...

Sorting in Ruby on rails


ruby-on-rails,json,sorting
I'm very new to Ruby on rails. I try to edit the following api. I want to sorting "can_go" which is true are shown at the top of list. I added this row before sending data, but the result is still order by "user_id". user_infos.sort { |a, b| - (a['can_go']<=>b['can_go'])...

Ranking with time weighting


python,algorithm,sorting,math
I am looking for a basic algorithm that gives more weigh to the recent reviews. So, the output value of the algorithm is mutable. For example, two reviews with exactly the same score, will have a different ranking based on the timestamp of the creation. Review_1 Score 10 creation 10/5/2014...

Ember passing a model to transitionToRoute


ember.js,ember-cli,ember-router,ember-controllers
I'm using Ember-cli with ember 1.11 I'm trying to use the transitionToRoute method in a controller to transition to a route and feed it a dynamically generated object as the model. Here's my controller: import Ember from 'ember'; export default Ember.Controller.extend({ actions: { launch_scanner: function(){ console.log('launch_scanner'); var model = {name:...

How do I remove duplicate objects in an array by field in Javascript?


javascript,arrays,sorting,object
I have an array of objects: [{ id: 1, name: 'kitten' }, { id: 2, name: 'kitten' },{ id: 3, name: 'cat }] How do I remove the second kitten? Sorting into an array of names doesn't work, because I can't know if I am deleting id 1 or or...

Sort multiple columns of Excel in VBA given the top-left and lowest-right cell


excel,vba,excel-vba,sorting
I am trying to sort these three columns (Sort By Col-2) in excel using VBA. Top-left (Row number and Column number e.g. 1,1) and lowest-right cell (Row number and Column number e.g. 9,3) are known. Every cell contains the values of String type. Input: Col-1 Col-2 Col-3 P1 I1 XYZ...

Assign two actions to one element in Ember.js


ember.js
<span {{action 'toggleChildren' 'ServerObjects'}} {{action 'contextMenu' on='contextMenu'}}>{{server.name}}</span> Unfortunatelly when I add this second action, the first one stops working. I can't find a way to assign two actions to one element. I found this topic: Ember : handling multiple events with {{action}} tag? . Does it still apply?...

Can we access Ember.TEMPLATES in controller?


javascript,templates,ember.js
Is it possible to use Ember.TEMPLATES to check the existence of a template within a controller or component? I am using v1.12.1 We are currently transitioning to a route that is rendering a template that may not exist. Prior to the transition, we need an existence check of the template...

Sort arrayList based on both date and ID


java,sorting
i want to sort the list of task,first by date and then by taskID below is the code ArrayList<fullist> taskdet = new ArrayList<fullist>(); public static class fullist { public int date; public int id; public fullist(int id, int date) { this.date = date; this.id = id; } } i used...

Find column with unique values move to the first column and sort worksheets


excel,vba,excel-vba,sorting
I have 2 worksheets with the same headers in different orders. Headers are I.D, Name, Department, Sales, Start date, End Date and a few others. What I am aiming to do is search through the workbooks in which the headers may be in different orders, find the column which has...

Sort array by keys in custom order


php,arrays,sorting
I have the following multidimensional array Array ( [June 2015] => Array ( [LOW] => Array ( [0] => 160.50 ) [MEDIUM] => Array ( [0] => 0.00 ) [HIGH] => Array ( [0] => 60.80 ) ) [July 2015] => Array ( [MEDIUM] => Array ( [0] => 226.00...

Refactoring Computed Properties on Ember.js 1.13


ember.js
I was able to upgrade most of my Ember.js project to 1.13 after having some issues along the way, but now I can't wrap my head around the following deprecated code: filteredPosts: function(){...}.property('var1','var2','var3') When I enable it, the only notice that I receive is: Uncaught TypeError: controllerClass.proto is not a...

How do I communicate the form parameters from the template to the route in ember.js?


forms,ember.js
I have a form like this in a template: <form {{action 'add' on='submit'}}> <label for="name">Name</label> {{input value=name placeholder='Enter name' required="required"}} </form> Then I have the following route: import Ember from 'ember'; export default Ember.Route.extend({ actions: { add: function() { alert(this.get('name')); } } }); The alert is fired, but the output...

Should checking loop conditions be counted towards total number of comparisons?


c++,algorithm,sorting,c++11
I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

Sort when values are None or empty strings python


python,list,sorting,null
I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

C# sorting arrays in ascending and descending order


c#,arrays,sorting
I'm having trouble writing a method that returns true if the elements of an array (numbers) are in sorted order, ascending or descending, and false, if they are not in any sorted order. I can return a correct boolean value if the array is ascending but i do not know...

How to get data out of ember objects


javascript,ember.js,kendo-grid
I'm fairly new to ember and I'd like to know whats the fastest way to extract the data out of ember objects. I've loaded my model with a very large amount of records using this.store.find('modelName);` in my route. I created a component on my view using {{kendo-ui.kendo-table descriptor=tableDescriptor data=model}}. My...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread


c++,multithreading,sorting,recursion
I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

Ember Simple Auth - injecting current user into every route


ember.js,dependency-injection,ember-simple-auth
I am building a site using Ember Simple Auth. I followed these instructions to try and add the current user object to the session and it worked, using this slightly adapted code: import Ember from 'ember'; import Session from 'simple-auth/session'; export default { name: "current-user", before: "simple-auth", initialize: function(container) {...

When creating a new data object in Ember that relies on another object how do you pass it along?


ember.js,ember-cli
I am on a page where I can see a specific customer, part of my router.js is: this.route('customers'); this.route('customer', {path: "customers/:customer_id"}); this.route('customer.order.create', { path: "customers/:customer_id/order/create" }); customer.order.create needs to load in my main view and so is not nested. An order 'has a' customer. I've setup my /customer/order/create controller to...

How to run action in Ember Controller afterRender


ember.js,ember-data,ember-cli
im new to ember framework. I just want to execute a function that defined inside the actions hook when the rendering completes. var Controller = Ember.Controller.extend({ actions: { foo: function() { console.log("foo"); } } }); Ember.run.schedule("afterRender",this,function() { this.send("foo"); } but the above code not working. I just want to know...

Given an array/object of datetimes, how can I return an array/object of the times sorted by hour and times sorted by days of the week


php,arrays,sorting,datetime,laravel
PHP/Laravel, I'm getting an array of objects that includes date times for each record. I need to generate analytics on objects on an hourly basis of a day and daily basis of a week. So for example: For a date range of 1/1/2015 - 1/10/2015 I return 100 records all...

SSRS re-sorts data meticulously sorted from the SQL query! Why?


sql-server,sql-server-2008,sorting,reporting-services
I'm writing up a report using SQL Server Reporting Service via Visual Studio 2008. I have a stored procedure on a SQL Server database that returns a list in which I need the entry with value "F" in colulmn [Column] to be always on top, as such: F A B...

Formatting a Pivot Table in Python


python,sorting,pandas,format,dataframes
I am trying to reformat a table based on counts in different columns. df = pd.DataFrame({'Number': [1, 2, 3, 4, 5], 'X' : ['X1', 'X2', 'X3', 'X3', 'X3'], 'Y' : ['Y2','Y1','Y1','Y1', 'Y2'], 'Z' : ['Z3','Z1','Z1','Z2','Z1']}) Number X Y Z 0 1 X1 Y2 Z3 1 2 X2 Y1 Z1 2...

Sum NA values in r


r,sorting,na
I am using a dataframe that has multiple NA values so I was thinking about sorting the attributes based on their NA values. I was trying to use a for loop and this is what I have so far: > data <- read.csv("C:/Users/Nikita/Desktop/first1k.csv") > for (i in 1:length(data) ) {...

sorting vector of pointers by two parameters


c++,sorting,vector
I am trying to sort a vector of pointers to a class A using std::sort, but am having some difficulties. Imagine class A beings just a point, containing x and y coordinates. I want to sort the vector by y coordinates from biggest to lowest using some fixed offset value....

In Ember 1.13 and later what key should I use with each when iterating over an array of strings?


ember.js,ember-cli
In Ember 1.13 the following code generates a warning: {{#each widgetNames as |widgetName|}} {{component widgetName removeWidget="removeWidget"}} {{/each}} Where widgetNames is an array of strings in a parent controller. widgetNames: [] In Ember 1.13 I now get this warning: WARNING: Using {{each}} without specifying a key can lead to unusual behavior....

Can ember-cli watch and build automatically without running the server?


ember.js,ember-cli
Title is pretty much my question. I'm serving the dist directory differently and would still like the benefit of auto-builds but I don't need to run the server. I looked in the docs and the cli help but didn't see anything specific. I know the cli help doesn't contain everything...

Associative array not storing first result from SQL


php,mysql,arrays,sorting
I have a database in MySQL and I'm using this query to select certain rows from it using PHP: $q = "SELECT Number, Body FROM boxes WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC"; Then calling the query and initiating arrays: $r = $mysqli->query($q); $row = mysqli_fetch_array($r, MYSQLI_ASSOC);...

Freeing array of dynamic strings / lines in C


c,string,sorting,malloc,free
I am writing a program that is sorting the lines from the input text file. It does its job, however I get memory leaks using valgrind. #include <stdio.h> #include <stdlib.h> #include <string.h> char* getline(FILE * infile) { int size = 1024; char * line = (char*)malloc(size); int temp; int i=0;...

Ember 1.13, view lookup


javascript,ember.js
Prior to ember 1.13 i was using var containerView = Em.View.views[view_id]; to get the ContainerView instance with the view id and manually adding childViews to this container view, which used to work just fine. As of ember 1.13 this view lookup is not supported. What is the recommended way of...

Merge multiple lists based on List priority


java,sorting,collections,priority
I have couple of lists where each list has different priority. When i merge these lists i should get with height priority on top. Assume i have 3 lists and different objects value common in 3 lists should come first and then the top priority list should be appended vice...

Mapping Ember methods to API


ember.js,ember-data,rails-api
I'm using Ember Data with a Rails API and am wondering how I can map specific actions from Ember to the API. For example, in looking at the Ember docs for deleteRecord and destroyRecord I see no mention of how these methods are translated to the backend. Is this configured...

What are Element Style Components and What are Fragment Style Components?


javascript,ember.js
I would like to know the difference between Element Style Components and Fragment Style Components ,precisely what is meant by Element Style Components and what is meant by Fragment Style Components? Thanks in advance.

Sort function giving floating point exception for a large input of 0's


c++,sorting,radix-sort,floating-point-exceptions
I have written a code for this problem: Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return...

Sorting a HTML structure


javascript,html,sorting
Im trying to sort a div structure based on a paramter using a small javscript i found. It seems to not perform exactly as expected. I understand the sorting function is not parsing the values perfectly... This is the sorting logic is use... <script type="text/javascript"> // Sorting Logic $(function() {...

WPF MVVM custom Sorting issue


c#,asp.net,wpf,sorting,mvvm
I am trying to create custom sorting WPF Data Grid. I have did database call on every sorting. I have used MVVM for this. Issue is I am always getting Sort Direction of column always null on sorting event when I make DB Call. If I remove UpdateData method from...

Algoritm to sort object by attribute value without allowing gaps or duplicates


python,sql,django,sorting,django-orm
I have a agenda with multiple dates, each date can contain 0 > ... items. Items can be sorted by position, positions should be Integer values without gaps and duplicates. class Item(models.Model): date = models.DateField() position = models.IntegerField() def move_to(position): qs = self.__class__.objects.filter(date=self.date) # if the position is taken, move...

ember-data stores a string instead of a number


ember.js,ember-data
In my ember app I want to reuse a model attribute as soon as the form is submitted. But the store seems to keep it as string unless I reload the whole route. I am using this and the following components: Ember : 1.12.0 Ember Data : 1.0.0-beta.18 jQuery :...

What's the best way to map objects into ember model from REST Web API?


json,rest,ember.js,asp.net-web-api,ember-data
The topic of this post is: my solution is too slow for a large query return. I have a Web Api serving REST results like below from a call to localhost:9090/api/invetories?id=1: [ { "inventory_id": "1", "film_id": "1", "store_id": "1", "last_update": "2/15/2006 5:09:17 AM" }, { "inventory_id": "2", "film_id": "1", "store_id":...

WPF Listbox Collection custom sort


wpf,sorting,listbox,compare,collectionview
I have a listbox DropPrice MyPrice Price1 Price2 I want to sort it like this Price1 Price2 DropPrice MyPrice I mean, if there's an item that starts with the sequence "price", it gets priority, else the smallest string should get the priority. My source code: var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource)); var...

Javascript sort array of objects in reverse chronological order


javascript,arrays,sorting
I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is...

elastic search sort in aggs by column


sorting,elasticsearch,group-by,order
I am trying to sort in elastic search in aggs, equivalent in mysql "ORDER BY Title ASC/DESC". Here is the index structure: 'body' => array( 'mappings' => array( 'test_type' => array( '_source' => array( 'enabled' => true ), 'properties' => array( 'ProductId' => array( 'type' => 'integer', 'index' => 'not_analyzed'...

Javascript Sorting Array of Objects [duplicate]


javascript,arrays,sorting,object
This question already has an answer here: Sorting an array of JavaScript objects 14 answers (Please excuse any errors - this is my first post and I am also relatively new to Javascript) I'm trying to sort an array of objects by a specific property value in Javascript. I...

Sort List of Numbers according to Custom Number Sequence


list,python-2.7,sorting
Question :A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Input Format: The first line will contain the the...

Sort four (4) javascript arrays with 10 objects each by a value


javascript,sorting
model w/ sample data => [{ date: '13413413', name: 'asdfasdf', other: 'kjh' }] getJSON returns 4 arrays of 10 model objects each. array1 = 10 of resultsObj sorted by date from newest to oldest array2 = 10 of resultsObj sorted by date from newest to oldest array3 = 10 of...