Can you guys help me understand how does this code check if inputed array sorted by ascending, descending or not sorted at all? I tried to understand it myself for two days but with no success
Here is the code
const arraySortInfo = (inputArray) => {
if (inputArray.some((element) => typeof element !== "number")) {
return "Some elements are not numbers";
}
if (
inputArray.every((element, index) =>
index > 0 ? element >= inputArray[index - 1] : true
)
) {
return "Array sorted by ascending";
}
if (
inputArray.every((element, index) =>
index > 0 ? element <= inputArray[index - 1] : true
)
) {
return "Array sorted by descending";
}
return "Array isn't sorted";
};
const a = [5, "abc", 10, 1];
const b = [4, 10, 14, 25, 25, 50];
const c = [150, 132, 80, 40];
const d = [15, 26, 10, 23, 85];
I specifically lost in this lines of code and the same one for descending
if (
inputArray.every((element, index) =>
index > 0 ? element >= inputArray[index - 1] : true
)
) {
return "Array sorted by ascending";
}
I tried to sit and write down everything on paper but so far I thought that I understood what it does with ascending, but then I tried to figure out descending check the same way and it didn’t add up so I must be wrong at something.
Here is how I understand it on ascending example
inputArray[4, 7, 10 for example].every((element, index) =>
first time index 0 > 0 ? element 4 >= inputArray*//4,7,10 = 2 indexes//*[index */0/* - 1] : true
*so if 4 >= 1 it return true*
second time index > 0 ? element 7 >= inputArray*//4,7,10 = 2 indexes//*[index */1/* - 1] : true
*if 7 >= 2 returns true*
third time index > 0 ? element 10 >= inputArray*//4,7,10 = 2 indexes//*[index */2/* - 1] : true
*if 10 >= 1 return true*
*and if every time this was true it will return "Array sorted by ascending"*
It worked here for me. But it didn’t work the same way for descending numbers so I must be wrong. Maybe I’m wrong about (element, index) inputs?