Is that supposed to be a function, or a value?
What is the instruction in step 1?
What I believe is happening is JavaScript coverts the boolean result of the comparison to a number. true becomes 1 and false becomes 0. This can be proven with:
Number(true) //=> 1
Number(false) //=> 0
Then it is applying the rules according to the MDN documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
- If
compareFunction(a, b)
returns 0, leavea
andb
unchanged with respect to each other, but sorted with respect to all different elements. - If
compareFunction(a, b)
returns greater than 0, sortb
to an index lower thana
(i.e.b
comes first).
Why did they choose to make the sort function so complicated?
return specArr.sort((a,b) => {
return a.numTeeth > b.numTeeth;
});
This leads to ascending order sorting. I read it as when a is larger than b push it into the array
, though the result is the complete opposite. Is anyone able to fully wrap their head behind this function and what it is really doing and what the logic is behind it and how it came about?
Good night
I have a problem. I know the excercise i supposed to be solved by using the .sort () method. But i tried to build my own comparison and i dont know why it does not work. Can someone help me understand why?
Thanks in advance!
const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}];
// Write your code here:
const sortedSpecies = [];
const sortSpeciesByTeeth = (array) => {
for (i=0; i<array.length; i++) {
if (array[i].numTeeth > array[i+1].numTeeth){
sortedSpecies.unshift(array[i]);
}
else {
sortedSpecies.push(array[i]);
}
};
return sortedSpecies;
};
console.log(sortSpeciesByTeeth(speciesArray));
Greetings,
Daniel
The simplest form of sort is Bubble Sort
and that requires two loops, one nested within the other. Your code is attempting to sort in a single pass which is not always possible, hence the need for nested loops.
Thank you for your quick respond. I will try to read into this bubble sort thing, just to satisfy my curiosity
You’re welcome. There are few topics on the forums, including this one…
Study the way the algorithm works. Once you get a clear picture it should be fairly simple to apply it to your solution. Keep us posted.
It worked for me like this!
function sortSpeciesByTeeth(speciesArray){
return speciesArray.sort((a,b) => a.numTeeth-b.numTeeth);
};
looking at the mdn documentation helped solve this
const sortSpeciesByTeeth = arr => {
arr.sort(function(a, b) {
return a.numTeeth - b.numTeeth;
})
return arr;
}
So… I guess I was way off, but I basically tried creating my own sort method from scratch. I was going to use nested for loops and I was basically going to create a new array, load the first element, and then compare the remaining elements of the passed array to all of the elements of the new array to find where they should be put. I’ve used push to add at the end, unshift at the beginning, and found splice could place an element anywhere in an array. The problem I’m having seems to be an infinite loop, but I’m not sure from where. I’m stepping through the arrays using a common method.
//given array
const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}];
//my code
const sortSpeciesByTeeth = animalArray =>{
const teethOrderArray=[];
//new array will always be empty, so always push first element
teethOrderArray.push(animalArray[0]);
//outer loop, steps through passed in array
for(let i=1; i < animalArray.length; i++){
//inner loop, compares each from the passed in with those previously sorted
for(let j=0; j < teethOrderArray.length; j++){
if(animalArray[i].numTeeth < teethOrderArray[j].numTeeth){
teethOrderArray.splice(j,0,animalArray[i]);
}
else if(i===animalArray.Length)
teethOrderArray.push(animalArray[i]);
}
}
return teethOrderArray;
}
console.log(sortSpeciesByTeeth(speciesArray))
// Should print:
// [ { speciesName: 'human', numTeeth: 32 },
// { speciesName: 'dog', numTeeth: 42 },
// { speciesName: 'shark', numTeeth: 50 },
// { speciesName: 'alligator', numTeeth: 80 } ]
HI there.
I got the fat arrow solution (as follows)
const sortSpeciesByTeeth = (arr) => arr.sort((a, b) => a.numTeeth - b.numTeeth)
but I wanted to break it down to an else if as the explanations of comparator functions I watched on youtube both used else if to show what is happening. After a very long time I got as far as making two separate functions (as follows)
function compareTeeth(a, b) {
if (a.numTeeth > b.numTeeth) {
return 1;
} else if (a.numTeeth < b.numTeeth) {
return -1;
} else {
return 0;
}
}
function sortSpeciesByTeeth(arr) {
return arr.sort(compareTeeth)
}
console.log(sortSpeciesByTeeth(speciesArray))
But I have no idea how to combie them into one or even if I should, can anyone tell me?
I also have one other question. I understand the logic of this problem, if a - b is positive switch them round and if not leave them be etc. I just don’t know how Javascript is understanding the logic of this from this code…
const sortSpeciesByTeeth = (arr) => arr.sort((a, b) => a.numTeeth - b.numTeeth)
Can anyone explain how that code translates into ‘if a - b is positive etc etc’? The only thing I have is that it may be to do with 1 and -1 being truthy and falsy?
This topic is really melting my brain, I am trying so hard to understand it but I’m not quite there.Thanks
In fact, both 1 and -1 are truthy since they are nonzero.
Your breakdown is correct. The JS sort()
method has this logic built in under the hood, along with the iteration, of course.
arr.sort((a, b) => a.numTeeth - b.numTeeth)
arr.sort((a, b) => a.numTeeth > b.numTeeth)
It is with that built in logic that it is able to arrive at the same result for both forms above.
const arr = [65, 12, 87, 34, 51, 93, 28, 10]
u = arr.sort((a, b) => a - b)
v = arr.sort((a, b) => a > b)
console.log(u)
console.log(v)
[ 10, 12, 28, 34, 51, 65, 87, 93 ]
[ 10, 12, 28, 34, 51, 65, 87, 93 ]
So is this just a case of accept that it does know what is happening in this instance (unless I want to get into the nut and bolts going on behind the scenes)?
Thanks for the speedy reply BTW, I appreciate it.
Accept is one word, understand is another. For our purposes usage is more critical than the under the hood mechanics. Knowing how to use a method given its known behavior is enough for most of us. As we advance into more esoteric studies we learn of several different sorting methods, along with the advantages/disadvantages of each. It’s clear that whomever put together the .sort()
algorithm had the acceptance of ECMA, hence it got written into the language.
Works for me. Thanks MTF
// My solution for this exercice
function sortSpeciesByTeeth(objArray)
{
const sortedArray = ;
const teeths=;
for (i of objArray){teeths.push(i.numTeeth)};
teeths.sort()
// console.log(teeths);
for(v1 of teeths)
{
for(v2 of objArray)
{
if( v1 === v2.numTeeth ){sortedArray.push(v2)};
};
}; return sortedArray
};
console.log(sortSpeciesByTeeth(speciesArray))
The code below shows various function approaches to sort by numTeeth and how to sort by speciesName. Note again when the keyword return is needed. See the MDN Array.prototype.sort() Description for details on sorting strings
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
Hope this is helpful! Best Regards, Bear . . .
Thank you for this. I had been working on this one for awhile. I forgot to add:
return arr;
This one made me feel like an idiot. I had been iterating through each object to find the integers in numTeeth and then sorting them. I think was completely confused on what the actually outcome of this project was supposed to be. Eventually, after researching .sort, I came up with:
arr.sort(function(a, b) {return a.numTeeth - b.numTeeth});
but kept getting an undefined return and absolutely could not figure out what the ■■■■ I was doing lol. It was a simple fix. Thank you again.
Hello programmers!
I solved the exercise thanks to the mozilla pages, i copied the sort() from the mozilla page, but i do not have very clear how it works.
const sortSpeciesByTeeth = (species) =>{
species.sort(function (a, b) {
return a.numTeeth - b.numTeeth;
}
);
return species;
}
In my understanding .sort(should sort the values of an array in order)…
i do not understand how can it “sort” things through calling a function… and if we look inside the function it returns the subtraction of the values “a.numTeeth to b.numTeeth”.
How can this result in a sorting?
I cannot follow the logic.
Who explains it to me please?