How to sort an array of posts by their elements?
You can’t sort using an optional value so if it is nil you need to supply a default value using ??. For sorting a min or max value is most suitable. Use min if you want to sort nil values last or max for the opposite
data.sort(by: { $0.price ?? Int.min > $1.price ?? Int.min })
Can you sort an array of react components? Accessing info of react componenet
What you have to do first is reduce
the allBands
array into an array of all the posts, without any nesting. To keep both the post
and band
values, you can just combine them into a single object. Then you can sort
it by date, however it is expressed in your data.
Doing anything with already created components is generally a bad idea and I would discourage it.
Here's the code:
{
bandTypes === "all"
? allBands
.reduce(
(allPosts, band) =>
allPosts.concat(
(band.youtube.length > 0 &&
band.bandBio !== "n/a" &&
band.bandGenre !== "n/a")
? band.posts.map((post) => ({ post, band }))
: []
),
[]
)
.sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
.map(({ post, band }) => convertPost(post, band))
: null;
}
You can find more information about reduce here.
How to sort an array by date that contains WP post objects created by merging get_posts results?
Merging the results of 2 separate queries won't change the order, so you will need to do a sort on them yourself.
Because because get_posts
returns an array of objects, we need to use a sort function that lets you create a user-defined comparison (e.g. usort
) - in other words we tell it what values to sort on and in what order.
If you are using PHP 7, you can use an anonymous function for the sort and the "spaceship operator" <=>
to do the comparison, so this is all you need:
usort($my_posts, function($post_a, $post_b) {
// Compare the post_date of the posts, and if $post_b is newer, then it will be displayed first
return $post_b->post_date <=> $post_a->post_date;
});
(Note that normally you would use return $a->value <=> $b->value;
to return the results in ascending order, but as we are working with dates and want the newest first, then we need to reverse the comparison to be return $b->value <=> $a->value;
)
So in your code, you just need to use it like this:
<?php
// do your merge...
$my_posts= array_merge( get_posts($args_b), get_posts($args_a) );
// sort the resulting array...
usort($my_posts, function($post_a, $post_b) {
return $post_b->post_date <=> $post_a->post_date;
});
// and now process the new sorted array as required.
foreach($my_posts as $post):setup_postdata($post);?>
<?php the_title(); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
UPDATE: If you are still using PHP 5 (which you shouldn't be!), you can use the following instead:
usort($my_posts, function ($a, $b) {
if ($a->post_date < $b->post_date) return -1;
elseif ($a->post_date > $b->post_date) return 1;
else return 0;
});
Sorting Javascript array of objects by one value
Try to use standard Array.sort() with compare function comparing the time property of each object.
let arr = [{"time": 1515892254405},{"time": 1515882632486}];
arr.sort(function(a, b) {return a.time - b.time}); // sorts in ascending order
console.log(arr);
arr.sort(function(a, b) {return b.time - a.time}); // sorts in descending order
console.log(arr);
Sort an array by comparison with values of another array
You could check if any of the tags of each object exists in tags
array using some
and includes
. Then subtract the value for 2 objects being compared.
const tags = ['one', 'two', 'three'];
let posts = [
{ tags: ['four', 'five'] },
{ tags: ['one', 'six'] },
{ tags: ['seven'] },
{ tags: ['nine', 'two'] },
];
posts.sort((a, b) =>
tags.some(t => b.tags.includes(t)) - tags.some(t => a.tags.includes(t))
)
console.log(posts)
How do I achieve an in-place sort on a sub range of elements in an ArrayT in swift?
The subscript operation that takes a range returns a mutable value. If you directly invoke a mutating method on it, it will mutate the original array in place:
var numbers = [3,5,2,4,1]
numbers[1..<4].sort()
print(numbers) // [3, 2, 4, 5, 1]
As of Swift 4.2, I think this is no more efficient than making a temporary copy of the slice (Source: forum post 1, forum post 2. These posts talk about all kinds of slicing operations incl. ones that change the length of the source collection, but it should be the same for in-place sorting.)
There've been a lot of under the hood changes for the upcoming Swift 5 release that aim to make this more efficient (background: ownership manifesto). In Swift 5, a setter (like a mutating subscript) can be modeled as a coroutine, which would allow to perform this kind of operation in place. But I'm not 100% sure if this will be the case in Swift 5.0.
Sorting a php array of arrays by custom order
You can use usort()
to dictate precisely how the array is to be sorted. In this case, the $order
array can be used within the comparison function.
The example below uses a closure
to make life easier.
$order = array(3452342, 5867867, 7867867, 1231233);
$array = array(
array('id' => 7867867, 'title' => 'Some Title'),
array('id' => 3452342, 'title' => 'Some Title'),
array('id' => 1231233, 'title' => 'Some Title'),
array('id' => 5867867, 'title' => 'Some Title'),
);
usort($array, function ($a, $b) use ($order) {
$pos_a = array_search($a['id'], $order);
$pos_b = array_search($b['id'], $order);
return $pos_a - $pos_b;
});
var_dump($array);
The key to this working is having the values that are being compared, be the positions of the id
s within the $order
array.
The comparison function works by finding the positions of the ids of two items to be compared within the $order
array. If $a['id']
comes before $b['id']
in the $order
array, then the return value of the function will be negative ($a
is less so "floats" to the top). If $a['id']
comes after $b['id']
then the function returns a positive number ($a
is greater so "sinks" down).
Finally, there is no special reason for using a closure; it's just my go-to way of writing these sorts of throwaway functions quickly. It could equally use a normal, named function.
Related Topics
Don't Delete Some Rows from Uitableview
Swiftui: Unexpected Animation When Using a Non @State Var
Swift How to Sort Dict Keys by Byte Value and Not Alphabetically
How to Sort an Array of Posts by Their Elements
Core Data Update in Swift While Selecting Any Row in List Table View Not Working
Swift Conforming Multiple Protocols Inherits from Same Protocol with Associated Type
Different Path Url for Filemanager Everytime I Open the App
How to Simultaneously Satisfy Constraints Error Whats Causing This
How to Ensure Make Sure I'm Not Accessing Data Until It's Loaded In
Color Ouput with Swift Command Line Tool
Swiftui How to Programatically Adjust Spacing Between Images and Text
Swift Can Not Save .M3U8 File to Gallery
Replace Multiple Words from a String Based on the Values in an Array
Ambiguous Method Overload with Closures in Swift, But Only When Closure Returns a Value
Swift 3 - How to Insert Tableviewcells from Another View
How to Set Up Multiple Combine Timer Publishers