Sort Strings
Javascript Examples
Button Reusable
function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
// Usage
<Button label="Submit" onClick={handleSubmit} />
Get Day of week
const getDayName = (date) => {
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
return days[date.getDay()];
};
console.log(getDayName(new Date())); // Friday
Get date
const getDate = () => new Date();
console.log(getDate()); // 2020-05-25T09:57:37.869Z
Convert to Object
const toObject = (arr) => ({ ...arr });
console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }
Remove Duplicates
const removeDuplicated = (arr) => [...new Set(arr)];
console.log(removeDuplicated([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ]
const removeDuplicate = (arr) =>
Object.values(arr.reduce((a, b) => (a[b] ? a : { ...a, [b]: b }), {}));
console.log(removeDuplicate([1, 2, 3, 3])); // Result: [ 1, 2, 3, ]
// program to check the number of occurrence of a character
function countString(str, letter) {
let count = 0;
// looping through the items
for (let i = 0; i < str.length; i++) {
// check if the character is at that position
if (str.charAt(i) == letter) {
count += 1;
}
}
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
SORT words in alphabetical order
- // take input
- const string = prompt('Enter a sentence: ');
- // converting to an array
- const words = string.split(' ');
- // sort the array elements
- words.sort();
- // display the sorted words
- console.log('The sorted words are:');
- for (const element of words) {
- console.log(element);
}