Let's say I have an array of objects like:
var posts = [{
queued: false,
score: 3
}, {
queued: false,
score: 2
}, {
queued: false,
score: 1
}, {
queued: 100,
score: 0
}, {
queued: 56,
score: 1
}]
I want to split up based on the queued
property, one array has all the queued: false
, the other has everything else. I then want to sort by score
and join them.
I can do the following:
let queuedPosts = _.filter(posts, function(post) {
return post.queued !== false;
});
let unqueuedPosts = _.filter(posts, function(post) {
return post.queued === false;
});
Then sort queuedPosts
by its property queued
, then unqueuedPosts
by score
, and posts = _.concat(queuedPosts, unqueuedPosts)
. This would not be scalable if I were to split by some other property in the future. What would be a cleaner way to do this?
EDIT: Code currently looks like this
sortPosts(posts) {
let queuedPosts = _.filter(posts, (post) => (post.queued !== false));
let unqueuedPosts = _.difference(posts, queuedPosts);
queuedPosts = orderBy(queuedPosts, 'queued', 'asc');
unqueuedPosts = orderBy(unqueuedPosts, 'score', 'desc');
return [...queuedPosts, ...unqueuedPosts];
}
I believe if I make use of the _.remove
method, I can programmatically use another object containing keys, sort order, and limits, I can modify this to dynamically sort depending on user's needs via an input like some checkboxes.