jadjoubran / codetogo.io

🚀 JavaScript code to go - Find updated snippets for common JavaScript use cases
https://codetogo.io
MIT License
231 stars 30 forks source link

Use Case Suggestion: How to check if an array is sorted? #141

Closed swapagarwal closed 6 years ago

jadjoubran commented 6 years ago

Thanks @swapagarwal 😄

nicksspirit commented 6 years ago

Do u mean like an array of numbers or what?

swapagarwal commented 6 years ago

Generic. It can be of strings too!

nicksspirit commented 6 years ago

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

nicksspirit commented 6 years ago

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

jadjoubran commented 6 years ago

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