1. Pick a random element from an array
const themes = ['neo', 'black & white', 'color'];
const randomNumber = Math.round(Math.random() * 100); // random number between 0 - 100
const randomElement = randomNumber % themes.length; // so that the number is within the arrays range
console.log(themes[randomElement]);
2. Find sum using reduce()
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((previousSum, element) => {
const newSum = previousSum + element;
return newSum;
}, 0); // Initially the sum is set to 0
console.log(sum); // 15
3. Capitalize the first letter of every word
const str = "code drops";
const capitalize = (input) =>
input
.split(" ") // split by spaces
.map((word) => word[0].toUpperCase() + word.slice(1)) // uppercase first character of every word
.join(" "); // join them back by spaces
capitalize(str); // Code Drops
4. Insert something in the middle of an array
const arr = [1, 2, 3, 4];
const index = 2;
const insertText = "hello";
// Solution 1 - Split at the index and rejoin them
const result = [...arr.slice(0, index), insertText, ...arr.slice(index)];
console.log(result); // [1, 2, 'hello', 3, 4]
// Solution 2 - .splice() - It can be used to add/remove elements from array
const arrCopy = [...arr]; // splice modified the array on which the operation is performed.
arrCopy.splice(index, 0, insertText); // arguments are - index, no of elements to remove, new element to add
console.log(arrCopy); // [ 1, 2, 'hello', 3, 4 ]
5. Array.filter()
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const numbersGreaterThanFive = numbers.filter(number => number > 5);
console.log(numbersGreaterThanFive); // [6, 7, 8, 9, 10]
6. Convert array to object using .reduce()
const list = [
{ label: "javascript", color: "blue" },
{ label: "html", color: "red" },
{ label: "css", color: "green" },
];
const initialValue = {};
const convertToObject = (result, item) => {
const language = item.label;
const color = item.color;
return {
...result,
[language]: color,
};
};
const palette = list.reduce(convertToObject, initialValue);
console.log(palette); // { javascript: 'blue', html: 'red', css: 'green' }
7. Check if a String is a Palindrome
const isPalindrome = (str) => str === str.split("").reverse().join("");
isPalindrome("codedrops"); // false
isPalindrome("racecar"); // true
8. Reverse a string
const reverse = str => str.split("").reverse().join("");
reverse('Codedrops.tech'); // hcet.spordedoC
9. Array.every()
Check if all the elements in the array are greater than 0
using .every()
const arr = [1, 2, -1, 4, -5];
const allGreaterThanZero = arr.every(number => number > 0);
console.log(allGreaterThanZero); // false
Thanks for reading 💙
Follow @codedrops.tech for daily posts.
Instagram ● Twitter ● Facebook
Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript
codedrops.tech
Top comments (2)
Honestly I couldn't get over capitilize. And capilatize. They are definitely the awesomest words ever, save for "awesomest"
Thankest You XD