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

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay