Menu
  • HOME
  • TAGS

Sort array of objects by subarray property value in javascript

javascript,arrays,sorting,sub-array

You can pass two different arguments to dynamicSort function function dynamicSort(property1,property2) { var sortOrder = 1; if(property1[0] === "-") { sortOrder = -1; property1 = property1.substr(1); } return function (a,b) { var result = (a[property1][property2] < b[property1][property2]) ? -1 : (a[property1][property2] > b[property1][property2]) ? 1 : 0; return result *...

Can't sort array of structures alphabetically

c,arrays,sorting,struct,structure

First of all, the algorithm you are trying to build is not sorting. What you have here is (after fixing issues described below) one iteration of bubble sort. To make it actually sort the array you need to call dictioarySort 10 times. See https://en.wikipedia.org/wiki/Bubble_sort for more details. Now to the...

Reading and listing objects in the order they appear in the source file in R

r,sorting,object,ls

There's no way to get the order of variable definition after sourcing the file without explicitly recording the order in the file itself. One way to do this would be to put the variables in a list.

File Handling and making directories to match in bash

bash,shell,sorting,matching,file-handling

#!/bin/bash # If there are no files match File_*.*.txt # replace File_*.*.txt by empty string shopt -s nullglob for i in File_*.*.txt; do echo "processing file $i" IFS="_." read foo num1 num2 foo <<< "$i" printf -v dir1 "Dir_%03d" "$num1" printf -v dir2 "Dir_%03d" "$num2" mkdir -pv "$dir1" "$dir2" cp...

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

javascript,jquery,sorting,jquery-datatables

Take a look at dataTables columns / columnDefs render() function. You can return various content or values depending on the purpose : filter, display, type or sort. If you want to sort the column by 0 / 1 based on the <span> has the classes .on or .off, you can...

MongoDB custom sorting with the other values?

javascript,mongodb,sorting

The most efficient approach would be to update the rank field when you change the values in your application code (i.e. don't allow time and velocity to be set without also recalculating the rank). You can then add an appropriate index (or indexes) including the rank field to support your...

sort runs out of memory

linux,sorting,memory,ram

I found the issue myself. It's fairly easy. The "tr -cd '[:print:]'" removes line breaks and sort reads line by line. So it tries to read all the files as one line and the -S parameter can't do its job.

Sorting or Arranging an Array with a standard array values

javascript,arrays,algorithm,sorting

This solution is pretty slow, but should work dbArray.sort(function(a,b) { return stdArray.indexOf(a) - stdArray.indexOf(b); }); If you're concerned about performance, you could use a map to track the index of each item to avoid scanning the array for each comparison. var indexMap ={}; stdArray.forEach(function(str) { indexMap[str]=stdArray.indexOf(str); }); dbArray.sort(function(a,b) { return...

Sort my str_repeat

php,sorting,repeat,alphabetical

SELECT id, ip, port, game FROM dayz_servers ORDER BY game Let the SQL order the results for you....

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

Issue with sorting algorithm - VB

vb.net,algorithm,sorting

your problem is this here: If timeArr(i) = txtTD1.Text Then txtR1.Text = count ElseIf timeArr(i) = txtTD2.Text Then txtR2.Text = count ElseIf timeArr(i) = txtTD3.Text Then ... see: everytime you look at the text-boxes from txtTD1 to txtTD8 - so when two of them have the same value you will...

Sorting entire csv by frequency of occurence in one column

python,sorting,csv,pandas,frequency

This seems to do what you want, basically add a count column by performing a groupby and transform with value_counts and then you can sort on that column: In [22]: df['count'] = df.groupby('CompanyName')['CompanyName'].transform(pd.Series.value_counts) df.sort('count', ascending=False) Out[22]: CompanyName HighPriority QualityIssue count 5 Customer3 No User 4 3 Customer3 No Equipment 4...

Sort 2 Arrays in Reverse in C#

c#,arrays,sorting

You can reverse the arrays with the Array.Revers method. public void Print() { Array.Sort(nScore, nPlayer); Array.Reverse(nScore); Array.Reverse(nPlayer); PrintKeysAndValues(nPlayer, nScore); } ...

C# sorting arrays in ascending and descending order

c#,arrays,sorting

It should be something like: public static bool IsArraySorted(int[] numbers) { bool? ascending = null; for (int i = 1; i < numbers.Length; i++) { if (numbers[i - 1] != numbers[i]) { bool ascending2 = numbers[i - 1] < numbers[i]; if (ascending == null) { ascending = ascending2; } else...

Emberjs advanced sort hasMany association as a computed property

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

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({ });...

java - Is JavaFX SortedList stable?

sorting,javafx

Yes it's stable. I ran a quick test on this data (converted to obsList): private static Student[] studentList = { new Student("Garcia", 19), new Student("Williams", 20), new Student("Johnson", 21), new Student("Davis", 22), new Student("Brown", 23), new Student("Brown", 21), new Student("Rodriguez", 20), new Student("Garcia", 18) }; Sorting it with this: new...

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

c++,algorithm,sorting,c++11

If you look at your inserstion sort As you already put count =1 because as for exits on exit condition of for loop. for same reason then it also make sense that when while loop cancels the count++ inside will not get executed but there was a comparison made. but...

Javascript Sorting Array of Objects [duplicate]

javascript,arrays,sorting,object

You use a custom callback with the array method .sort(). Arr.sort(function(a, b) { return a.age - b.age; }); MDN reference page on .sort(). And, here's a working snippet: var Obj1 = {firstName: "John", lastName: "Doe", age: 46}; var Obj2 = {firstName: "Paul", lastName: "Smith", age: 22}; var Obj3 = {firstName:...

XSLT sort by attribute and attribute value (with exclude)

sorting,xslt,attributes,xslt-1.0,alphabetical

I am not entirely sure if this meets your requirements, but you could explicitly select the ones you want to come first in a separate xsl:apply-templates, then select the others with a sort on their type attribute <xsl:apply-templates select="orderEntry[@type='specific' or @type='other']" /> <xsl:apply-templates select="orderEntry[@type!='specific' and @type!='other']"> <xsl:sort select="@type" order="descending" />...

Efficiently sorting large arrays of people by their proximity to the user

javascript,arrays,sorting,mobile,latitude-longitude

It all has to be tested but here are some ideas that I would try. For heavy use of trigonometric functions you can use lookup tables. This is always a good idea. For example precompute 360 (or more) values of sin() and for every sin(radians) in your code use sinTable[degrees]....

sort list of objects in VB.NET by two elements

vb.net,list,sorting,object

You could implement a custom IComparer(Of Passenger) for List.Sort: Class PassengerComparer Implements IComparer(Of Passenger) Public Function Compare(p1 As Passenger, p2 As Passenger) As Integer Implements System.Collections.Generic.IComparer(Of Passenger).Compare If p1.Age = p2.Age AndAlso p1.Name = p2.Name Then Return 0 ElseIf p1.Age <> p2.Age Then Return p1.Age.CompareTo(p2.Age) ElseIf p1.Name <> p2.Name Then...

odd results from nested for loops javascript

javascript,arrays,sorting,object

I think you are using splice incorrectly, regardless this is a bit over complicated try: for (var i in word) { var w = word[i].innerHTML; if (ls.indexOf(w)> -1) { word_string += w; } } ...

sorting an array in the same line as instantiation/initialization

java,arrays,sorting,initialization

Not same line. But you can do: public static int[] sort(int[] a) { Arrays.sort(a); return a; } // ... int[] age = sort(new int[] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22}); ...

Sort array by keys in custom order

php,arrays,sorting

You could use the following comparison function: function cmp($a, $b) { $order = Array( 'LOW' => 0, 'MEDIUM' => 1, 'HIGH' => 2 ); return $order[$a] - $order[$b]; } Example of this code is here....

sorting vector of pointers by two parameters

c++,sorting,vector

(b->y < a->y - offset) || (b->y > a->y + offset) These are two different cases, which should have different results. I suppose that b is "less" then a in first case, and "greater" in the other case, but your code returns false for both cases. See @Jonathan's answer on...

How to sort arrays with multiple items - Javascript

javascript,arrays,sorting

Sort the elements based on [0]th index. (array4).sort(function(a, b){return a[0]-b[0]}) function myFunction(){ array4.push(array1, array2, array3); alert((array4).sort(function(a, b){return a[0]-b[0]})); } ...

Python custom sort

python,sorting,python-3.x

Python already has the wrapper you describe, it's called functools.cmp_to_key

How sorting parts of array my cause the whole array to be sorted

arrays,sorting

When L = N - K, the whole array could be sorted.

How to sort multidimentional array

c++,c,sorting,for-loop

use qsort version #include <cstdio> #include <cstdlib> #define N 5 using namespace std; int cmp(const void *a, const void *b){ int *x = (int*)a; int *y = (int*)b; return (*x > *y) - (*x < *y); } int main(){ int a[N] = { 3, 6, 2, 4, 1 }; int...

Sort when values are None or empty strings python

python,list,sorting,null

If you want the None and '' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be...

Improving a sort program's efficiency; displaying column sort % completion in terminal

python,perl,sorting,unix

From your sample data, you are going to sort approximately 950MB. It will take 9.5s reading from normal HD (100MB/s). I do not know how fast it will be sorted by standard sort but from my experience it can go 1-3 millions of records per CPU core. Let's say 1...

Sorting table created by PHP, can't use query to sort

php,mysql,sorting

Combine queries 2 and 3 with a join. By using an inner join you only get a row if the join is successful. ie: select tti.* from $table_tester_config ttc inner join $table_tester_info tti on tti.board_id = ttc.board_id where td.device = '$device_name' and td.tester_type = '$tester_type' order by tti.tester_name Then loop...

Sorting issue: i have li and i want it to sort by clicking on Asc and Desc

jquery,html,sorting

try this:- $(function() { $('#asc,#desc').click(function() { var $sort = this; var $list = $('#test'); var $listLi = $('li',$list); $listLi.sort(function(a, b){ var keyA = $(a).find('span').text(); var keyB = $(b).find('span').text(); if($($sort).is('#asc')){ return (keyA > keyB) ? 1 : 0; } else { return (keyA < keyB) ? 1 : 0; } });...

Freeing array of dynamic strings / lines in C

c,string,sorting,malloc,free

There are multiple problems in your code: function getline: the string in the line buffer is not properly '\0' terminated at the end of the do / while loop. It does not free the line buffer upon end of file, hence memory leak. It does not return a partial line...

Sorting imported text file?

python,sorting

put the data as tuples in a list. then sort the list descending by score. file = open("classj.txt") classj = (file.readlines()) s = [] for line in sorted(classj): classj = (line.rstrip()) classa = (classj.split("-")) score = int(classa[1]) name = (classa[0]) s.append( (name,score) ) s.sort(reverse=True, key=lambda x:x[1]) for x in s:...

How can I tell how many times these nested statements will execute?

algorithm,sorting,big-o,time-complexity,complexity-theory

The outer for-loop would run for n times. But, it also holds an inner for-loop which is dependent on the vale of j. I think that the first for-loop test will execute n times, and the nested for-loop will execute 1 + 2 + ... + n = n(n+1)/2 times....

WPF MVVM custom Sorting issue

c#,asp.net,wpf,sorting,mvvm

Since you're marking the event as Handled (e.Handled = true), you're effectively preventing the DataGrid from sorting and the SortDirection is never changing. You'll have to manage the sort direction yourself. But it should be as easy as this: private ListSortDirection lastSortDirection; private string lastSortMemberPath; public async void Sorting(DataGridSortingEventArgs e)...

Elasticsearch - Order search results ASC

c#,sorting,elasticsearch,nest

This example is working, maybe it will put some light on your issue. var indicesResponse = client.DeleteIndex(descriptor => descriptor.Index(indexName)); client.CreateIndex(indexName, c => c .AddMapping<Exhibitor>(m => m .MapFromAttributes() .Properties(o => o .MultiField(mf => mf .Name(x => x.CompanyName) .Fields(fs => fs .String(s => s.Name(t => t.CompanyName).Index(FieldIndexOption.Analyzed).Analyzer("standard")) .String(s => s.Name(t =>...

Sort an array based on another array's values in PHP

php,arrays,sorting

If i understood correctly $Array1 = array("myfirst_value", "mysecond_value", "mythird_value"); $Array2 = array ( 4 => myfirst_value, 8 => myforth_value, 21 => mysecond_value, 7 => myfifth_value, 17 => mysixth_value, 20 => mythird_value, 16 => myseventh_value ); // Remove elements of the 1st array from the 2nd function f ($v) { global...

Java - order things in an arraylist according to an atribute

java,sorting,arraylist

You could do this using a Comparator<Call> class, one whose compare(Call c1, Call c2) method compares the attributes of interest of the two parameters and then returns 1, 0 or -1 depending on the results of the comparison. You can then use Collections.sort(myList, myComparator) to sort your collection based on...

WPF Listbox Collection custom sort

wpf,sorting,listbox,compare,collectionview

You just have to check if it starts with "price". Note that I don't think that ToString() is appropriate; you should rather implement IComparer<T> and strongly type your objects in your listbox. public int Compare(object x, object y) { // test for equality if (x.ToString() == y.ToString()) { return 0;...

java 8 stream groupingBy sum of composite variable

java,sorting,java-8,grouping,java-stream

Unless I'm mistaken, you can not do both sorts in one go. But since they are independent of each other (the sum of the nothings in the Anythings in a Something is independent of their order), this does not matter much. Just sort one after the other. To sort the...

Sorting in Ruby on rails

ruby-on-rails,json,sorting

You're not getting the results you want because you're not assigning the sorted user_infos back into the user_infos variable. You can do the following: user_infos = user_infos.sort {|a, b| - (a['can_go'] <=> b['can_go']) } # -or- user_infos.sort! {|a, b| - (a['can_go'] <=> b['can_go']) } The first version of sort creates...

Finding a number that is sum of two other numbers in a sorted array

arrays,sorting,find,sum

Here I am doing it using C: An array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x. METHOD 1 (Use Sorting) Algorithm: hasArrayTwoCandidates (A[], ar_size, sum) 1) Sort the array in non-decreasing order. 2) Initialize...

Sorting based on the rules set by a string variable

c++,qt,sorting,c++11

You can make a map between their choice and a functor to sort by, for example using SortFun = bool(*)(Hotel const&, Hotel const&); std::map<char, SortFun> sorters { {'s', [](Hotel const& lhs, Hotel const& rhs){ return lhs.stars < rhs.stars; }}, {'f', [](Hotel const& lhs, Hotel const& rhs){ return lhs.freeRoomCount < rhs.freeRoomCount;...

elastic search sort in aggs by column

sorting,elasticsearch,group-by,order

Edit to reflect clarification in comments: To sort an aggregation by string value use an intrinsic sort, however sorting on non numeric metric aggregations is not currently supported. "aggs" : { "order_by_title" : { "terms" : { "field" : "title", "order": { "_term" : "asc" } } } } ...

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

excel,vba,excel-vba,sorting

To find and move the "ID" column like 1th column Sub movecolumn() Dim sht As Worksheet Dim keySrc As String Dim lastcol As Long, cutCol As Long Dim arrcol As Variant Set sht = ThisWorkbook.Worksheets("Sheet1") keySrc = "ID" lastcol = sht.Cells(1, sht.Columns.Count).End(xlToLeft).Column 'find the last Headers columns arrcol = Range(Cells(1,...

Merge multiple lists based on List priority

java,sorting,collections,priority

This produces the result you expect. It won't handle more than 63 lists at a time. The alogorithm is based on weights that are combinations of the powers of 2, each list being associated with another power of two. Thus, an element from the first list (of n lists) with...

Sort List of Numbers according to Custom Number Sequence

list,python-2.7,sorting

This matches your input/output examples, but I had to use descending numbers to get the example answers. Are you sure your explanation is correct? If not, just use 0123456789 instead of 9876543210 in the code below. The algorithm is to provide a sorting key based on translating the digits of...

Associative array not storing first result from SQL

php,mysql,arrays,sorting

$row = mysqli_fetch_array($r, MYSQLI_ASSOC); You are getting first returned row by this line. You have to remove it and it will work properly. mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call....

WPF Listview sort works only one time, and then nothing happen

c#,wpf,sorting,listview

Check if you didn't copy-paste columns with the same tag in xaml.

How to implement mergeSort?

java,sorting,mergesort

Suppose you input a vector of size 2; then according to your code mid=1; for(int i=0;i<mid-1;i++) // here i < (1-1) which will never execute l[i]=v[i]; ...

How to sum columns in R according to categories in 2 different groups

r,sorting

Use one of the aggregating functions library(data.table) setDT(df1)[,list(Production=sum(Production)) , .(Municipality,Type)] # Municipality Type Production # 1: Atima Reverification 1030 # 2: Comayagua Initial 484 # 3: Comayagua Reverification 307 # 4: Copán Initial 279 # 5: Copán Reverification 377 # 6: Danlí Reverification 56 or res <- aggregate(Production~., df1, FUN=sum)...

Sorting a list with dictionaries, django

python,django,list,sorting,dictionary

You should just be able to do: sorted_objects = sorted(objdict, key=lambda k: k['thing1']) will get you ascending order. For descending: sorted_objects = sorted(objdict, key=lambda k: k['thing1'], reverse=True) ...

Sorting a HTML structure

javascript,html,sorting

I took at look at your live site and injected the sorting function you used in your question. I noticed a few things. Firstly, the strings you are passing into your compare function look like this: "£38.89 ex. VAT" "£19.93 ex. VAT" "£44.44 ex. VAT" ... So parseInt("£38.89 ex. VAT")...

Sort Array by Date and Size (Files)

java,arrays,sorting

Sorting functions. Modify them as needed. All they are doing is make use of values and compareTo() method calls. The key to understanding this is available here. String logic together as needed to form your function for your sort as it is slightly confusing on what the actual sort requirements...

Comparison method violates its general contract when sorting

java,sorting,comparison

This is one example of the sort of change that I think is needed. As @CommuSoft pointed out in a comment, the current treatment of null for o1 and o2 breaks transitivity. I would replace: if (o2 == null || o1 == null) return 0; with: if (o2 == null...

Update and sort Qt ComboBoxes alphabetically

c++,qt,sorting,combobox

You're trying to use QComboBox's internal model as source model for proxy. This is not going to work because QComboBox owns its internal model and when you call QComboBox::setModel, previous model is deleted (despite you reset its parent). You need to create a separate source model. Conveniently, you can use...

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

javascript,sorting

This will be easy to understand for you. first concatenate the array into one and chain the output to Array.sort code var result = a.concat(b,c,d).sort(function(a, b) { return b.date-a.date }); ...

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

python,sql,django,sorting,django-orm

The above algorithm would not work , because assume you have the following list - [0,2,5,9] You should ideally get - [0,1,2,3] The sum of that list is 6 , but the length of the list is 4 , this does not meet your condition in is_compressed() . The algorithm...

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

excel,vba,excel-vba,sorting

I got the solution after going through many tutorials and hence posting here for reference of any one who needs help. Sub testSort() Dim CurrentSheet As Worksheet Set CurrentSheet = ActiveSheet lastRows = CurrentSheet.Cells(Rows.Count, 1).End(xlUp).Row lastCols = CurrentSheet.Cells(1, Columns.Count).End(xlToLeft).Column Set sortA = CurrentSheet.Range(Cells(2, 1), Cells(lastRows, lastCols)) CurrentSheet.Sort.SortFields.Clear CurrentSheet.Sort.SortFields.Add Key:=Range(Cells(2, 2),...

Using linux sort on multiple files

linux,sorting

I assume you have many input files, and you want to create a sorted version of each of them. I would do this using something like for f in file* do sort $f > $f.sort done Now, this has the small problem that if you run it again, if will...

Wrong column filtering for date column

javascript,sorting,formatting,filtering,tablesorter

You are seeing two things happen here: When entering a number in the filter that is not a valid date, a string comparison is done. So that is why the first row matches. Because the filter_defaultFilter for column 1 is set to use a fuzzy search filter_defaultFilter: {1: '~{query}'} a...

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

You can use Laravel's collection groupBy method to group your records for your needs. $records = YourModel::all(); $byHour = $records->groupBy(function($record) { return $record->your_date_field->hour; }); $byDay = $records->groupBy(function($record) { return $record->your_date_field->dayOfWeek; }); Remember that this code to work, you have to define your date field in the $dates Model array, in...

Does MongoDB find() query return documents sorted by creation time?

database,mongodb,sorting

No. Well, not exactly. A db.collection.find() will give you the documents in the order they appear in the datafiles host of the times, though this isn't guaranteed. Result Ordering Unless you specify the sort() method or use the $near operator, MongoDB does not guarantee the order of query results. As...

Sorting a dictionary value which is a list of objects by given fields

c#,linq,sorting,dictionary

You can use List.Sort, LINQ doesn't work in this case because you can't modify the dictionary(f.e. Add or using the Value property) during enumeration: foreach(var kv in yourSortedDictionary) { kv.Value.Sort((p1, p2) => { int diff = p1.LastName.CompareTo(p2.LastName); if(diff != 0) return diff; return p1.FirstName.CompareTo(p2.FirstName); }); } This works even if...

12 Hour Clock Array Sort

php,arrays,sorting,time,clock

strtotime will accept that format. So you can use a custom sort (usort) with a strtotime based callback. usort($array, function($a, $b) { return (strtotime($a) > strtotime($b)); }); ...

Formatting a Pivot Table in Python

python,sorting,pandas,format,dataframes

You will need a custom mode function because pandas.Series.mode does not work if nothing occurs at least twice; though the one below is not the most efficient one, it does the job: >>> mode = lambda ts: ts.value_counts(sort=True).index[0] >>> cols = df['X'].value_counts().index >>> df.groupby('X')[['Y', 'Z']].agg(mode).T.reindex(columns=cols) X3 X1 X2 Y Y1...

“sort not a function” error in angularjs only in google chrome

javascript,angularjs,google-chrome,sorting

Your response is not an Array. It could be an object with a property that contains the Array (e.g. response.data) or a string version of you array and then you will need to use JSON.parse and convert the string into an Array. Anyway, sort is on Array's prototype - that...

sorting of month in matrix in R

r,sorting,matrix

Suppose DF is the data frame from which you derived your matrix. We provide such a data frame in reproducible form at the end. Ensure that month and year are factors with appropriate levels. Note that month.name is a builtin variable in R that is used here to ensure that...

How to sort the cards in each hand from the card values first and then the suits in C?

c,sorting

As Shay Gold said, it is simpler to use an int for the value of the cards. Edit: His method is described at the end of this post, his method seems to automatically make a suit sort inside a value sort. You can define values from 0 to 51: cards...

Change part of link with jquery

javascript,jquery,ruby-on-rails,ajax,sorting

Ideally you would use jQuery.hasClass or jQuery.is to determine if an element has the specified class or classes. You also need to update the display before navigation or form submit. You can do all this: $('.sort-link-css > a').click(function(e) { // cancel the click event on the link e.preventDefault(); var $this...

Sort a string alphabetically using a function

javascript,sorting

You can use array sort function: var sortAlphabets = function(text) { return text.split('').sort().join(''); }; STEPS Convert string to array Sort array Convert back array to string Demo...

How to implement custom sort for koGrid?

javascript,sorting,knockout.js,typescript,kogrid

Just try to modify your code like this View : <div data-bind="koGrid: gridOptions"></div> viewModel: vm = function () { var self = this; self.myData = ko.observable([{ hours: '113.02 hours' }, { hours: '13.01 hours' }, { hours: '303.01 hours' }, { hours: '33.01 hours' }]); self.gridOptions = { data: self.myData,...

Adding a new Worksheet in its Alphabetically correct position

excel,vba,sorting

I understand the workbook is already sorted and that a new sheet must be inserted in the alphabetical order, copied from a template sheet. The following code will do that: Sub InsertSheet(name As String) Dim i For i = 1 To ActiveWorkbook.Sheets.Count If ActiveWorkbook.Sheets(i).name >= name Then Exit For End...

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

javascript,arrays,sorting,object

there is the lodash library. You could use the uniq var array = [{ id: 1, name: 'kitten' }, { id: 2, name: 'kitten' },{ id: 3, name: 'cat' }]; var asd = _.uniq(array,'name'); console.log(asd); Gives an output: [ { id: 1, name: 'kitten' }, { id: 3, name: 'cat'...

Sort arrayList based on both date and ID

java,sorting

This will work: Collections.sort(taskdet, new Comparator<Fullist>() { @Override public int compare(fullist o1, fullist o2) { int res = Integer.compare(o1.date, o2.date); if(res == 0) return o1.id - o2.id return res; } }); ...

Sum NA values in r

r,sorting,na

The right way to do iterative code in R is to avoid explicit for loops. Use apply (and the company) instead. @jeremycg gave you the right R-ish answer. Regarding your code, you should make some editing to make it work. temp <- c() for (i in 1:length(data)){ temp[names(data)[i]] <- sum(is.na(data[i]))...

How to sort a variable-length string array with radix sort?

string,algorithm,sorting,radix-sort

I'm not quite sure what you mean by "variable-length strings" but you can perform a binary MSB radix sort in-place so the length of the string doesn't matter since there are no intermediate buckets. #include <stdio.h> #include <algorithm> static void display(char *str, int *data, int size) { printf("%s: ", str);...

Sorting networks costs and delay

sorting,sorting-network

From what I can see, your answer is correct. Cost is the total number compare exchanges done in the sorting network. I believe here it's 28. Delay is the number of stages that must be done in sequence, i.e. have data dependencies. In the example there is a delay of...

NSTableView - how to get automatic and manual sorting working together?

osx,swift,cocoa,sorting,nstableview

I will be damned but the reason for the error is obviously that the property is read-only. So adding a setter, or better yet, change the code to simply: var customSortDescriptors = [NSSortDescriptor(key: "string", ascending: true, selector: "localizedStandardCompare:")]; fixed the error and both, automatic and manual sorting works....

C++ lib in Python: custom sorting method

python,c++,sorting

The error is quite clear: ctypes doesn't know how to convert a python list into a int * to be passed to your function. In fact a python integer is not a simple int and a list is not just an array. There are limitations on what ctypes can do....

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

sql-server,sql-server-2008,sorting,reporting-services

Have you checked both the Tablix Properties and the Column Group properties for sorting? The Column Grouping's sort takes Priority...and additionally will automatically include a clause to sort on the same field that the Group is on, which usually accounts for confusion like this in my experience.

Sorting vector of Pointers of Custom Class

c++,sorting,c++11,vector

The only error that I see is this>current_generation_.end() instead that ->. In addition you should consider declaring your compare fuction as accepting two const FPGA* instead that just FPGA*. This will force you to declare fitness() as const int fitness() const but it makes sense to have it const. Mind...

How do you build the example CUDA Thrust device sort?

c++,visual-studio-2010,sorting,cuda,thrust

As @JaredHoberock pointed out, probably the key issue is that you are trying to compile a .cpp file. You need to rename that file to .cu and also make sure it is being compiled by nvcc. After you fix that, you will probably run into another issue. This is not...

Determine sorting algorithm from results

algorithm,sorting

We can tell that this isn't a quadratic-time algorithm like selection sort or insertion sort, since raising the input size by a factor of 10 raised the runtime by a factor of 13-19. This is behavior we'd expect from an O(n*log(n)) average-case algorithm, like mergesort or a good quicksort. We...

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

c++,multithreading,sorting,recursion

You problem originates in this line: int newArray[maxCount + 1]; You are trying to allocate ~250000 ints on the stack (on most 32 bit platforms it will take ~1MB of memory). Your thread's stack may not be able to do this. By the way, you should not do this -...

How to swap two dates in swift

arrays,swift,sorting,swap

This function is named sort, but it doesn't actually sort the array. If you're actually trying to sort the array, you should just use the builtin sort function: missions.sort { $0.createdAt.timeIntervalSince1970 > $1.createdAt.timeIntervalSince1970 } The function as you've written it, were it compilable, would always cause a fatalError because you...

Ranking with time weighting

python,algorithm,sorting,math

To clarify @Dan Getz and add @collapsar answer I will add the following: Dan's Formula is correct: (score1 * weight1 + ... + scoreN * weightN) / (weight1 + ... + weightN) The beauty of the weighted average is you get to choose the weights! So we choose days since...

Sorted List for Doubly Linked List

python,list,sorting,doubly-linked-list

If you want a list to remain sorted, ensure that you insert elements into it in sorted position. Finding this position should be straightforward. The doubly linked list class, has only a Double Ended Queue (dequeue) interface, so insertion isn't actually possible with the current methods and you will need...

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

c++,sorting,radix-sort,floating-point-exceptions

Your radixSort function violates the Compare requirements, namely irreflexivity (that is, radixOrder(x, x) must return false but it returns true because the execution goes to the first if branch). So you get a classic example of undefined behavior here. I believe that piece of code should be rewritten somehow like...

Read words/phrases from a file, make distinct, and write out to another file, in Java

java,file,sorting,distinct-values

You can leverage: NIO (Non-blocking I/O) API (available since Java 7) Streams API (available since Java 8) …to solve the problem elegantly: public static void main(String... args) { Path input = Paths.get("/Users/yourUser/yourInputFile.txt"); Path output = Paths.get("/Users/yourUser/yourOutputFile.txt"); try { List<String> words = getDistinctSortedWords(input); Files.write(output, words, UTF_8); } catch (IOException e) {...