Question is:
Write a function which takes a sentence as an input and output a sorted sentence.
Each character of the word should be arranged in alphabetical order
Words should be arranged in ascending order depending on its character count
Note: - Word only can have lowercase letters
Example :
Inputs str = "she lives with him in a small apartment"
Output = "a in ehs him hitw eilsv allms aaemnprtt"
the error is
// running test
"message: The answer should be valid for any given input."
// tests completed
my code:
function makeAlphabetSentenceSort(str) {
str.toLowerCase();
var word = str.split(' ');
for (var j = 0; j < word.length; j++) {
word[j] = word[j].split('').sort().join('');
}
for (var h = 0; h < word.length - 1; h++) {
for (var i = 0; i < word.length - h - 1; i++) {
if (String(word[i]).length > String(word[i + 1]).length) {
var temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
}
}
}
return word.join(' ');
}
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));
console.log(makeAlphabetSentenceSort("she lives with him in apartment"));
This looks like an exercise from a course so I won't give you the exact implementation but I will say this:
JavaScript has some nice abstractions that will help.
Arrays
use String.split().
"my string".split(' ') to make an array of words."someword".split('') to make an array of characters.Arrays can be iterated
Use Array.map() to iterate through an array and return something for each item.
Arrays can be sorted
Use Array.sort() to do any sorting of arrays.
Try the following:
function makeAlphabetSentenceSort(str) {
var word = str.split(' ');
for (var j = 0; j < word.length; j++) {
word[j] = word[j].split('').sort().join('');
}
return word.sort((a, b) => a.length - b.length).join(' ');
}
console.log(makeAlphabetSentenceSort('he was curious about how it would taste, so he took a small bite.'));
The problem with that question is that they do not follow their own rules which states
Word only can have lowercase letters
that said a sentence with punctuation could run through the code.
So, to be able to pass this challenge, you're also going to need to swap words of the same length with each other.
Hope you find this helpful!