Closed swapagarwal closed 6 years ago
Do u mean like an array of numbers or what?
Generic. It can be of strings too!
Well in that case the code will need to know how to check if the array is sorted. So like if you have an array of ints, you need to provide some predicate to tell it if it should check that these array of ints should be sorted.
Same goes for strings
Here is an example:
let xsInt = [1,2,3,4,5,56]; // asc => false, desc => true
let xsIntReversed = [56, 5,4,3,2,1]; // asc => true, desc => false
let xsString = ['a', 'ant', 'cat', 'dog']; // asc => false, desc => true
let xsStringRevesed = ['dog', 'cat', 'ant', 'a']; // asc => true, desc => false
const desc = (a, b) => a < b;
const asc = (a, b) => a > b;
const val = xsStringRevesed.every((el, index, arr) => {
if (index === arr.length-1) return true;
return asc(arr[index], arr[index+1]);
});
console.log(val) //=> true
In javascript strings are sorted lexicographically
Thanks @OdinTech3 This seems like a function for 30-seconds-of-code rather than codetogo as we try to keep our use cases very simple rather than giving developers a "ready-to-copy" function
Thanks @swapagarwal 😄