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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay