Sort by Status then by date JavaScript - javascript

I have an array of the following type I wan to sort. I want to sort them by the status and show false ones first and and then sort them by their date. I don't know if I should use group by then sort.
"itemlist": [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}]
I have used the below code it sorts the array by status but the date sorting is not working. can someone help me with a better method and what am I doing wrong ? , Thanks
var res=itemlist.sort((a, b) => (a.Status === b.Status ) ? 0 : a.Status ? 1 : -1 || b.Date- a.Date);

The reason is that your date is string format,not actually date,you need to change it to date when compare
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date));
also,you expression is too complex to read and debug,had better to use () to wrap it or use if else condition instead
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));
working code
var itemlist = [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}];
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));
//output the sorted result
console.log(res);

Related

Sorting HTML Tables in JavaScript using Regex

I'm trying to make a HTML table sorting system in JavaScript. All I want is to sort each column by clicking on it, but I think I have to use regex to do so. You see, I want to sort numbers (0-9) first, then sort it alphabetically (a-z) then everything else (special characters) and last empty cells.
This is the order it has to go.
1
03
5
data
data1
-data
-data1
*empty cells*
*empty cells*
The code underneath can only sort the empty cells to the bottom (Code currently taken from Sorting HTML table with JavaScript):
var getCellValue = function(tr, idx) {
return tr.children[idx].innerText || tr.children[idx].textContent;
}
var comparer = function(idx, asc) {
return function(a, b) {
return function(v1, v2) {
if (v1 == "")
return 1;
if (v2 == "")
return -1;
return v1 != "" && v2 != "" && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}
};
Array.prototype.slice.call(document.querySelectorAll("th.sortable")).forEach(function(th) {
th.addEventListener("click", function() {
var table = th.parentNode
var tbody = document.querySelector("tbody")
while (table.tagName.toUpperCase() != "TABLE") table = table.parentNode;
Array.prototype.slice.call(tbody.querySelectorAll("tr"))
.sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(function(tr) {
tbody.appendChild(tr)
});
})
});
Does anyone know a simple solution to my problem?

Sorting a string from part of string using jquery

Below is a list of array.I want the strings in array sorted only by airlines. For example below are my
airlines
"0:"FZ|Fly Dubai "1:"LH|Lufthansa "2:"IX|Air India Express
"3:"6E|IndiGo
Expected output should be which is sorted only by arilines ( Air
India Express, Fly Dubai, Lufthansa, Indigo instead of complete
string
"0:"IX|Air India Express "1:"FZ|Fly Dubai "2:"LH|Lufthansa
"3:"6E|IndiGo
I have tried something like this
str = str.split('|');
str = str.sort(function (a,b) {
if (a === '0' || b === '0')
return (b === a) ? 0 : (a < b) ? 1 : -1;
return (a < b) ? -1 : (a === b) ? 0 : 1;
});
let airlines = [
"FZ|Fly Dubai",
"LH|Lufthansa",
"IX|Air India Express",
"6E|IndiGo",
];
let sorted = airlines.sort(function(a, b) {
return a.split('|')[1].localeCompare(b.split('|')[1]);
});
console.log(sorted);
No jQuery needed.
Assuming s = '"0:"FZ|Fly Dubai "1:"LH|Lufthansa "2:"IX|Air India Express "3:"6E|IndiGo'
s.split(/\"[^\"]+\"/) // regex parses entries
.filter( // removes invalid entries
function(a){
return a.length > 0 && a.indexOf("|") > -1
}).sort( // sorts based on airline name
function(a,b){
return a.split("|")[1] > b.split("|")[1]
});
To get it back in the initial format, you could then map. ie:
let i = 0;
s.split(/\"[^\"]+\"/) // regex parses entries
.filter( // removes invalid entries
function(a){
return a.length > 0 && a.indexOf("|") > -1
}).sort( // sorts based on airline name
function(a,b){
return a.split("|")[1] > b.split("|")[1]
}).map( // map puts it back in original state, but ordered
function(z){
return '"'+(i++).toString()+':"' + z;
});

multiple sorting using knockout checkboxes

I am trying to organize a observablearray that has inside 2 boolean ​​values and a price. I need via knockout and 2 checkboxes, filter the elements by these two values. Also sort by price ( ascending and descending) the displayed values . I don't put any code because I'm new in knockout and I can't see the way to make these actions.
Appreciate someone who instructed me.
Simple answer, I tried with this, but making some changes on my personal viewModel to supply my needs. So, I make something like this:
self.elementsToShow = ko.pureComputed(function () {
// Represents a filtered and ordered list of elements
var recomend = self.showRecommended(); //chekbox 1
var special = self.showSpecial(); // checkbox2
var sorting = self.currentSortDirection(); //sort direction: price or rating //ascending or descending, represented by an observableArray with that conditions and the //selectedSortDirection
if (!recomend && !special) return self.myOservableArray().sort(function (a, b) {
//in case that no one of the checkboxes where selected but the sort direction was't by default
if (sorting.price != null) {
var fp = sorting.price ? -1 : 1;
ap = parseInt(a.price);
bp = parseInt(b.price);
return ap == bp ? 0 : (fp * (ap < bp ? -1 : 1));
}
else if (sorting.rate != null) {
var f = sorting.rate ? -1 : 1;
ar = parseFloat(a.rating);
br = parseFloat(b.rating);
return ar == br ? 0 : (f * (ar < br ? -1 : 1));
}
});
return ko.utils.arrayFilter(self.myOservableArray(), function (element) {
return (element.recommended != "0" && recomend) || (element.offer != "" && special); //some other conditions for the relection of the checkboxes in the observableArray
}).sort(function (a, b) {
if (sorting.price != null) {
var fs = sorting.price ? -1 : 1;
ap = a.price;
bp = b.price;
return ap == bp ? 0 : (fs * (ap < bp ? -1 : 1));
}
if (sorting.rate != null) {
var fu = sorting.rate ? -1 : 1;
ar = a.rating;
br = b.rating;
return ar == br ? 0 : (fu * (ar < br ? -1 : 1));
}
});
}, self);

javascript broken syntax

Alright, I or someone I work with broke the syntax here somewhere, and I'm not sure where, as the debugger is giving me some random garble as the error. Anyway here is the function, I think I'm missing a bracket somewhere, but this is just evading me for some reason.
var sort_by = function(field, reverse, primer) {
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B) ? -1 : (A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
}
there's an extra closing parenthesis on the line
return ((A < B) ? -1 : (A > B) ? +1 : 0))
should be
return ((A < B) ? -1 : (A > B) ? +1 : 0) ...etc
It would be useful if could provide the debugger error anyway. I exectued it in Chrome Developer Console and it gave the error:
SyntaxError: Unexpected token )
Which made it easy to find this broken line:
return ((A < B) ? -1 : (A > B) ? +1 : 0)) * [-1,1][+!!reverse];
You have unbalanced parenthesis. It should be:
return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1,1][+!!reverse];
There's one extra closing bracket here. Remove it.
return ((A < B) ? -1 : (A > B) ? +1 : 0)) * [-1,1][+!!reverse];
Also, semicolon everything.
var sort_by = function(field, reverse, primer) {
var key = function(x) {
return primer ? primer(x[field]) : x[field];
};
return function(a, b) {
var A = key(a), B = key(b);
return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1, 1][+!!reverse];
};
};

javascript sort array

My array isn't being sorted properly. Can someone let me know what I am doing wrong?
...
sortArray = new Array ("hello", "Link to Google", "zFile", "aFile");
//sort array
if (dir == "asc") {
sortArray.sort(function(a,b){return a - b});
} else {
sortArray.sort(function(a,b){return b - a});
}
for(var i=0; i<sortArray.length; i++) {
console.log(sortArray[i]);
}
the log is showing them in the same order as they were entered.
You want to make a comparison in your sort, not a subtraction:
if (dir == "asc") {
sortArray.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return a === b ? 0 : a > b : 1 : -1;
});
} else {
sortArray.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return b === a ? 0 : b > a : 1 : -1;
});
}
I also used toLowerCase() so that 'Link to Google' is placed appropriately.
EDIT: Updated to fix comparison issue according to comment.
See example →
You're trying to sort by subtracting strings, to which you'll get NaN.
The trouble is that "a - b" is treating the strings like numbers, which returns NaN. You will get the behavior you are looking for (assuming you are looking for case-sensitive sorts) if you replace your sorts with:
if (dir == "asc") {
sortArray.sort(function(a,b){return a < b ? -1 : 1});
} else {
sortArray.sort(function(a,b){return b < a ? -1 : 1});
}
Your comparator functions returns NaN, since it receives two strings, and performs subtraction, an operation that isn't well-defined on strings.
What you should have is something more like:
function(a,b){
return a>b? 1 : (a<b ? -1 : 0);
}
or you can use localeCompare:
function(a,b){
return a.localeCompare(b);
}
Remember to treat case appropriately, e.g. "L" < "a" whilst "l" > "a"

Categories

Resources