Sorting Object Arrays With JavaScript [duplicate] - javascript

This question already has answers here:
Why is one string greater than the other when comparing strings in JavaScript?
(5 answers)
How does sort function work in JavaScript, along with compare function
(7 answers)
Closed 4 years ago.
I have an array:
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]
and I want to sort cars object on type using this code
function myFunction() {
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
displayCars(); // a function to output the result
}
x and y in this function is either saab, bww or volvo. How is it possible to compare (saab < bmw). I mean they are not numbers to be compared and return another number.
How does if conditional statements compares two strings rather than comparing numbers? and why does it has to return -1, 1 and zero?

Are you asking why this works?
If so, it works because JavaScript has some awareness of lexicographical order. B comes before S and S comes before V and so on.
-1 means that variable a should be moved one index lower than variable b.
1 means that variable a should be moved one index higher than variable b.
0 means that variable a should not be moved.

Related

Postfix operator in JavaScript [duplicate]

This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 4 years ago.
This is a basic JS question I think, but I just couldn't find an answer that I was satisfied with. I'm learning operators in JavaScript and I can't understand this following postfix example and how it works:
var x = 4;
var y = x++;
For example, when I alert x, it gives me 5. But when I alert y, it gives me 4. And I can't understand the logic behind it.
I understand that, because it's a postfix, x is assigned to y. And y reads just x, without the postfix. But why does then the original x read the postfix instead if I'm applying it to a different var?
If I just did var y = x + 1, the original x would stay unchanged. But that's not the case when I use postfix. Why would I even change the x with this method? Couldn't I just go then var x = 4; x++; ? And not bother changing it via another var?
I apologize if this is too basic and thanks in advance!
It's easier to think of the increment operators as little functions that return something. So x++ is a functions that increments x and returns the original value of x, whereas ++x does the same thing but returns the new value.
This comes in handy from time to time especially in loops where you want precise control of the stopping point. For example, compare:
let i = 0, j = 0;
while (++i < 5) {
console.log(i) // stops at 4
}
while (j++ < 5) {
console.log(j) // stops at 5
}
The difference is because the while loop evaluates one before the increment and the other after.
Similarly in recursive functions you'll often see things like:
function recurse(i) {
if (i == 5) return i
console.log(i)
return recurse(++i)
}
console.log("final: ", recurse(0))
But if you use the postfix return recurse(i++) you get infinite recursion.
Why would I even change the x with this method?
For some funny shortforms like:
const array = [1, 2, 3];
let i = 0;
while(i < array.length) console.log(array[ i++ ]);
Couldn't I just go then var x = 4; x++; ?
Yeah or just prefix, like ++x or just x += 1 which is more appropriate in most cases.

This Javascript if statement won't run when using not operator? [duplicate]

This question already has answers here:
Is there a “not in” operator in JavaScript for checking object properties?
(6 answers)
Closed 5 years ago.
I'm trying to return an object with each letter from a string as a key, and each key's value being the amount of times that letter appears.
The if statement doesn't seem to execute, I think it's a problem with the not operator because I can get it to execute if I remove it and put the letter in the object so that it evaluates to true.
function multipleLetterCount(str){
var countObj = {};
for(var i = 0; i < str.length; i++){
//Why won't this if statement run???
if(!str[i] in countObj){
countObj[str[i]] = 1;
} else {
countObj[str[i]]++;
}
}
return countObj;
}
multipleLetterCount("aaa")
It returns {a: NaN}
You need to wrap your condition with the negation operator (!)
if(!(str[i] in countObj))
Or even better, invert your condition:
if (str[i] in countObj) {
countObj[str[i]]++;
} else {
countObj[str[i]] = 1;
}

Why is the argument passed in to my recursive function not updating its value? [duplicate]

This question already has answers here:
What does x++ in JavaScript do?
(4 answers)
Closed 5 years ago.
I'm just playing around with simple recursion and functions. Nothing too serious, but not doing what I expect:
var recursive = function adder (x) {
x = ++x
if (x < 10) {
console.log('x is now: ' + x)
adder(x)
}
return x
}
console.log(recursive(5))
This completes the loop and runs properly, but am wondering why the 'final' output is '6.' Why don't I get the 'final' value of x after all the recursion is done?
x=++x;
x+=1;
x++;
++x;
You need either the pre increment or the increase by operator, or the postincrement without an reassignment. The post increment retuns first, then increments...
alert((1)++)//1
Some ongoing explanations:
var recursive = function adder (x) {
++x;
if (x < 10) {
console.log('x is now: ' + x)
return adder(x); //lets return our added result
}
return x;//if x=10 lets return 10
}
console.log(recursive(5))//will log 10
It mainly didnt work as expected as primitives are passed by value. So there are actually 5 different x variables in 5 different contexts of adder...
Unlike primitives, objects are passed by reference:
function adder(obj){
obj.x++;
if(obj.x<10){
adder(obj);
}
}
var test={x:1};
adder(test);
console.log(test.x);

Variable changes by itself [duplicate]

This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 5 years ago.
I have a small problem trying to code a snake game in js.
I have this function:
function move() {
var aux = [];
aux = snake.position[snake.position.length - 1];
console.log(aux);
if (snake.direction == 'r') {
snake.position[snake.position.length - 1][1] += 1;
};
console.log(aux);
//updateSnake();
snake.position[snake.position.length - 2] = aux;
updatePosition(snake.position);
};
The problem is that aux is changing itself without me doing anything to it, as you can see. The value from the first console.log is different from the second one! It's not like I'm changing its prototype.
Can you guys help me?
if (snake.direction == 'r') {
snake.position[snake.position.length - 1][1] += 1;
}
The above line is what changes the array aux. The first console.log() returns [10,12] as stated in the above comments. After that, the if statement is incrementing snake.position[snake.position.length - 1][1], which is the value of the variable. When calling console.log() for the second time, the variable aux is evaluated as [10,12+1], equivalent to [10,13], which is the expected result.

Sort Array based on Object Attribute - Javascript [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 9 years ago.
I have an array of objects called canvasObjects.
Each object has an attribute called z.
I want to sort this array based on objects z. How do I do this using the sort() method?
You just need to pass in a comparator to the sort function
function compare(a,b) {
if (a.attr < b.attr)
return -1;
if (a.attr > b.attr)
return 1;
return 0;
}
canvasObjects.sort(compare);
Or inline
canvasObjects.sort(function(a,b) {return (a.attr > b.attr) ? 1 : ((b.attr > a.attr) ? -1 : 0);} );
See this POST
Tried other answers posted here but then I found the following to work best.
Ascending :
canvasObjects.sort(function(a,b) { return parseFloat(a.z) - parseFloat(b.z) } );
Descending :
canvasObjects.sort(function(a,b) { return parseFloat(b.z) - parseFloat(a.z) } );
Send anonymous function to the sort method which returns a subtraction of the property "z"
var arr = [{z:2},{z:4},{z:5},{z:1},{z:3}];
arr.sort(function(a,b) {return a.z - b.z});
above puts numbers in z to order 1,2,3,4,5. To reverse the order make it return "b.z - a.z".

Categories

Resources