DEV Community

Ismael Garcia
Ismael Garcia

Posted on

Easy to use JavaScript snippets.

1.- Sort an array.

//strings
const names = ["Hello", "How", "Where"];
names.sort();
//['Hello', 'How', 'Where' ]

//Numbers
const numbers = [5, 1, 87];
numbers.sort((a, b) => {
  return a - b;
});
//[ 1, 5, 87 ]

//Sort array based on object:

data.sort((a, b) => a.name > b.name ? 1 : -1)

Enter fullscreen mode Exit fullscreen mode

2.- Select a random element.


const elements = ["Hell", "Can", "Use"];

const getRandomIndex = Math.floor(Math.random() * elements.length);

elements[getRandomIndex];

Enter fullscreen mode Exit fullscreen mode

3.- Reverse a string.

const reverseString = (string) => string.split("").reverse().join("");

//Example
const stringReverse = reverseString("drag and drop a cover image");

Enter fullscreen mode Exit fullscreen mode

4.- Check if element has class.


const $elHaveClass = 
        (el, className) => el.classList.contains(className);

// Example
//Check if the sidebar is open
const $elSidebar = document.querySelector(".sidebar");


const isSidebarOpen = $elHaveClass($elSidebar, 'sidebar__open');

Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay