Reputation:
I want to make a string in alphabet order using javascript.
example, if string is "bobby bca" then it must be "abbbbcoy" but I want it in a function - take not that I dont want spaces to be there just alphabet order.
I'm new to javascript here is what I have already:
function make Alphabet(str) {
var arr = str.split(''),
alpha = arr.sort();
return alpha.join('');
}
console.log(Alphabet("dryhczwa test hello"));
Upvotes: 2
Views: 10959
Reputation: 1609
The function:
function makeAlphabet(str) {
var arr = str.split('');
arr.sort();
return arr.join('').trim();
}
An example call:
console.log(makeAlphabet("dryhczwa test hello"));
// returns "acdeehhllorsttwyz"
Explanation:
Line 1 of makeAlphabet
converts the string into an array, with each character beeing one array element.
Line 2 sorts the array in alphabetic order.
Line 3 converted the array elements back to a string and thereby removes all whitespace characters.
Upvotes: 0
Reputation: 642
There are a few things wrong with this code as the comments under your post mentioned.
once that is out the way then your code is correct and actually makes things alphabetical
About the spaces you want removed then you can use regex inside the function to remove the spaces and make it output just the characters in alphabetical order like this:
function makeAlphabet(str) {
var arr = str.split(''),
alpha = arr.sort().join('').replace(/\s+/g, '');
return alpha;
}
console.log(makeAlphabet("dryhczwa test hello"));
Other than that this is what I could make of your question
This is updated based on the comment and here is the fiddle: https://jsfiddle.net/ToreanJoel/s2j68s4s/
Upvotes: 2
Reputation: 18734
you start from a string like
var str ='dryhczwa test hello';
create an array from this
var arr = str.split(' ');
then you sort it (alphabetically)
var array = arr.sort();
and you join it back together
var str2 = array.join(' ');
Upvotes: 2
Reputation: 5917
Your function name cannot have spaces;
function makeAlphabet(str) {
return str.split('').sort().join('');
}
Plus, this won't remove spaces, so your example
console.log(makeAlphabet("dryhczwa test hello"));
Will return ' acdeehhllorsttwyz'
.
Upvotes: 0