Sort a collection of objects by number (highest first) then by letter (alphabetical)
countries.sort_by do |country|
medals = country.gold + country.silver + country.bronze
[-medals, -country.gold, -country.silver, country.name]
end
How to sort by Numbers first then Alphabetical
If you have always a single letter, you could sort by the numerical rest and by the first letter.
const
array = ["B3", "D2", "F1", "A9", "D12", "A2", "C1", "Z0", "B1"];
array.sort((a, b) => a.slice(1) - b.slice(1) || a[0].localeCompare(b[0]));
console.log(...array);
How to sort an array of objects with alphabets first and then with numbers in react
Check the types if both strings, sort them. If both numbers sort them. If different, move string before.
var arr = [{
"Acr": 502,
}, {
"Acr": "AO",
}, {
"Acr": "AW",
}, {
"Acr": 402,
}
];
arr.sort((a,b) => {
var tA = typeof a.Acr;
var tB = typeof b.Acr;
if (tA === tB && tA === "string") {
return a.Acr.localeCompare(b.Acr);
} else if (tA === tB && tA === "number") {
return a.Acr - b.Acr;
} else {
return tA === "string" ? -1 : 1;
}
});
console.log(arr);
Trying to sort array by numbers first and then letters last
You can try to compare them like this
product_data.sort(function(a, b) {
return a.itemCommodity > b.itemCommodity;
});
And if you want the order of the letters to be sorted then you can try this
product_data.sort(function(a, b) {
return a.itemCommodity.toLowerCase() > b.itemCommodity.toLowerCase();
});
Sort By Alphabet then Numbers Laravel Collection
You need to define your own custom comparator function to sort these collection objects using sort
.
Compare both names by checking they are all alphabets. If both are alphabets, then usual string comparison using strcasecmp
shall suffice. If either of them is an alphabet, push them to higher ranks by returning value -1
, meaning to be placed above in the sorted order. If both are numerical or alphanumeric, use strcasecmp
again.
<?php
$collection = collect([
['name' => 'b', 'symbol' => '#'],
['name' => '2a', 'symbol' => '$'],
['name' => '1', 'symbol' => '@'],
['name' => 'a', 'symbol' => '%']
]);
$collection = $collection->sort(function($a,$b){
$a_is_alphabet = preg_match('/^[a-zA-Z]+$/', $a['name']) === 1;
$b_is_alphabet = preg_match('/^[a-zA-Z]+$/', $b['name']) === 1;
if($a_is_alphabet && $b_is_alphabet){
return strcasecmp($a['name'], $b['name']);
}elseif($a_is_alphabet){
return -1;
}elseif($b_is_alphabet){
return 1;
}
return strcasecmp($a['name'], $b['name']);
});
Sort objects in an array alphabetically on one property of the array
you would have to do something like this:
objArray.sort(function(a, b) {
var textA = a.DepartmentName.toUpperCase();
var textB = b.DepartmentName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
note: changing the case (to upper or lower) ensures a case insensitive sort.
Sort array by firstname (alphabetically) in JavaScript
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
It should return
- something negative if first argument is less than second (should be placed before the second in resulting array)
- something positive if first argument is greater (should be placed after second one)
- 0 if those two elements are equal.
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
Example:
users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
This code is going to work with any type.
Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc. when you compare strings, so you may want to use localeCompare
. See other answers for clarity.
Sort and group objects alphabetically by first letter Javascript
You can create object with reduce
and then use Object.values
on that object.
let rawData = [
{ name : 'Animals', id : 10},
{ name : 'Batteries', id : 7},
{ name : 'Baggage', id : 12 },
{ name : 'Cake', id : 7},
]
let data = rawData.reduce((r, e) => {
// get first letter of name of current element
let group = e.name[0];
// if there is no property in accumulator with this letter create it
if(!r[group]) r[group] = {group, children: [e]}
// if there is push current element to children array for that letter
else r[group].children.push(e);
// return accumulator
return r;
}, {})
// since data at this point is an object, to get array of values
// we use Object.values method
let result = Object.values(data)
console.log(result)
Sort Counter by frequency, then alphabetically in Python
It sounds like your question is how to sort the entire list by frequency, then break ties alphabetically. You can sort the entire list like this:
>>> a = sorted(letter_count.items(), key=lambda item: (-item[1], item[0]))
>>> print(a)
# [('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]
If you want the output to be a dict still, you can convert it into a collections.OrderedDict
:
>>> collections.OrderedDict(a)
# OrderedDict([('a', 2),
# ('b', 1),
# ('e', 1),
# ('h', 1),
# ('l', 1),
# ('p', 1),
# ('t', 1)])
This preserves the ordering, as you can see. 'a'
is first because it's most frequent. Everything else is sorted alphabetically.
Sorting an NSArray of Objects by Letter then number
This
var arr = ["A6", "A2", "3", "B4", "L8", "4", "B7"]
let sortedArr = arr.sort({String($0) < String($1)})
print(sortedArr)
Will print out
["3", "4", "A2", "A6", "B4", "B7", "L8"]
Related Topics
Notices for Sequence After Running Migration in Rails on Postgresql Application
How to Traverse Symlinked Directories in Ruby with a "**" Glob
Ruby Gets/Puts Only for Strings
Heroku: Gemfile.Lock Is Required Issue
How to Identify Aliased Methods in Ruby
Uninitialized Constant "Controller Name"
What's the Best/Easiest Gui Library for Ruby
Combine Array of Array into All Possible Combinations, Forward Only, in Ruby
How to Remove a Node with Nokogiri
Why Can't I Access a Local Variable Inside a Method in Ruby
Ruby Block to String Instead of Executing
How to Insert a String into a Textfile
Ruby Gem Dependencies on Offline Server
Getting Uninitialized Constant Error When Trying to Run Tests