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

Top comments (0)