i am merely just curious if he is using this to iterate over the entire array. i always had a feeling this is what -1 did but i want the correct answer since assuming will get me nowhere but mistakes. Appreciate any assistance.
m.sort(function(a, b){
if(a === b) {
return 0;
}
if(typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
});
It is being used because sort expects the callback to indicate if a was less than (-1), equal to (0) or larger than (1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Related
I am trying to find out the value of the second variable in the if statement without knowing what the variable is.
EX:
//a, b, and c are controlled by the user in input boxes.
let a = "Josh"
let b = "James"
let c = ""
if (a.length!== 0 && b.length !== 0|| a.length !== 0 && c.length !== 0){
Here I want to check if a equals the value that the length doesn't equal 0. In this case b.
Ex:
if (a == secondVariable){
alert("WOOH")
}
I know I can write
if (a.length !== 0 && b.length !== 0){
if (a == b){
alert("WOOH")
}
} else if (a.length !== 0 && c.length !== 0){
if (a == c){
alert("BOOH")
}
} else {
alert("")
}
But this is a lot of code and I have a lot more variables to check in my code. Is there a more efficient way to write this? Thank you
You can combine the ifs. Also you only need to check the length of one thing if you are also comparing it vs other thing. Also there is a shortcut coercing the length property to a boolean:
if (a.length && a == b) {
alert("WOOH");
}
if (a.length && a == c) {
alert("BOOH");
}
So I was doing a code problem online and one of the solutions showed the following
function electionsWinners(votes, k) {
var max=Math.max(...votes)
var r=votes.filter(x=>x+k>max||x===max).length
return k?r:r==1?1:0
}
I don't think the specifics of the problem are relevant, I'm more interested in how the return statement works. I don't understand at all what gets returned, it seems that 2 ternary operators are being used but I'm not sure, can anyone help me understand how exactly this return statement functions?
Yes 2 ternary operators
return k?r:r==1?1:0
i will put the code with complete IF
if(k) //not is null
return r;
else
{
if(r==1)
return 1;
else
return 0;
}
If you convert it to if else statement then you'll better understand what's going on:
if (k) {
return r;
} else if (r === 1) {
return 1;
} else {
return 0;
}
Or
if (k) {
return r;
}
if (r === 1) {
return 1;
}
return 0;
You can look at
k?r:r==1?1:0
as a single expression. Each ? is connected to its immediately following :, so it's equivalent to:
k ? r : (r==1 ? 1 : 0)
where the second conditional operator takes effect only if the k is falsey. In that second conditional, if r is 1, 1 is returned, else 0 is returned.
Might be clearer with indentation:
return (k
? r
: (r == 1
? 1
: 0
)
);
The first test is k ? is k not 0/undefined/null? If so, return r (r) else : if r is 1 (r==1 ?) return 1 (1) otherwise return 0 (0))
I've been reading similar posts all day but can't figure out how to sort my javascript array by multiple properties.
My array has a 'name' and 'type' property.
To sort by name I now use:
byNameDesc.sort(function (a, b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return y < x ? -1 : y > x ? 1 : 0;
});
Works great. I want to enhance this function. If 'name' is 'foo' it should always be on top. And I also want to sort by 'type'.
So 'foo' should always be on top, next sort by 'name' and 'type'.
I tried this:
byNameDefault.sort(function (a, b) {
if (a.name == 'foo') {
return -1;
}
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
return x < y ? -1 : x > y ? 1 : 0;
});
But that didn't work.
And I have no clue how to sort by 'name' AND 'type'.
Any help is much appreciated.
For multiple sort criteria you proceed from the first to the last criterion:
If the two entries for one criterion are not equal, you can return from the sort function with result -1 or 1. Additionally at the last criterion you also can return 0 for two equal inputs.
Here is an example implementation for your case:
byNameDefault.sort(function (a, b) {
// compare names
var na = a.name.toLowerCase();
var nb = b.name.toLowerCase();
if (na !== nb) {
if (na === 'foo')
return -1;
else if (nb === 'foo')
return 1;
else
return na < nb ? -1 : 1;
}
// compare types
return a.type < b.type ? -1 : a.type > b.type ? 1 : 0;
}
Do this in one expression where the different components are combined with ||; only when one part evaluates to 0, then next one comes into play:
byNameDefault.sort(function (a, b) {
return (b === 'foo') - (a == 'foo') ||
a.name.localeCompare(b.name) ||
a.type.localeCommpare(b.type);
}
I'm sorting an Array alphabetically using this :
contactList.sort((function(index){
return function(a, b){
return (a[index] == b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2));
It works great, the only problem is that numbers and special characters appear at the top of my array. I would like it to be sorted alphabetically, but I also want it to store the numbers & special chars at the end.
I really have no idea how to modify my function in order to do this.
Just check, whether are they letters or not.
I'm checking only first character, but maybe you'll need to extend this check for case
a[index].charAt(0) == b[index].charAt(0) to compare following letters and so on in loop.
contactList.sort((function(index){
return function(a, b){
var aIsLetter = a[index].charAt(0).match(/[a-z]/i),
bIsLetter = b[index].charAt(0).match(/[a-z]/i);
if (aIsLetter && !bIsLetter) return -1;
if (!aIsLetter && bIsLetter) return 1;
return (a[index] == b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2));
Say I have a list of items, which are sorted using a given comparator. I would expect that after sorting into ascending order comparator(element[1], element[1+n]) should return -1 for all values of n> 1, because according to that comparator, element[1]
I am performing a custom sort and finding that after sorting there are instances where comparator(element[1], element[1+n]) returns 1. When I look at the instance I see that the comparator giving the correct output, i.e. element[1]>element[1+n]. I don't understand how this could be the case after performing a sort with that comparator.
If anyone has any idea of sort subtleties that I might have missed, I'd really appreciate their thoughts. Also, if I can provide more information that might shed light please let me know.
edit
I thought this might be a more general question, but in response to mplungjan have added the custom sorter below.
The sort is for a hierarchical dataset in the form of a flat list of objects. Each object has an id which might be as follows:
0 for root 1.
0-0 for its first child.
0-1 for its second child.
etc.
Each object in the list had a field 'parent' which has the id of its parent. Essentially data.sort isn't doing what I think it should be.
function CurrencyTreeSorter(a, b) {
a_id = a.id.split("-");
b_id = b.id.split("-");
if(a_id.length != b_id.length || a_id.slice(0, a_id.length-1).toString() != b_id.slice(0, b_id.length-1).toString()){
var i = 0;
while (i < a_id.length && i < b_id.length && a_id[i] == b_id[i]) {
i++;
}
if (i == a_id.length || i == b_id.length){
return a_id.length > b_id.length ? 1 : -1;
}
else{
while (a.level > i) {
a = getParent(dataMap, a);
}
while (b.level > i) {
b = getParent(dataMap, b);
}
}
}
var x, y;
if (a[sortcol] == "-") {
x = -1;
}
else {
x = parseFloat(a[sortcol].replace(/[,\$£€]/g, ""));
}
if (b[sortcol] == "-") {
y = -1;
}
else {
y = parseFloat(b[sortcol].replace(/[,\$£€]/g, ""));
}
return sortdir * (x == y ? 0 : (x > y ? 1 : -1));
}
This turned out to be an issue with Chrome, described here and here. Essentially it's not safe to return zero from the comparator/comparer.