2

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"));
3
  • 1
    What is your question? Commented Jun 1, 2015 at 13:24
  • Your function has two names (function make Alphabet)? And also, you want to remove all spaces? Commented Jun 1, 2015 at 13:24
  • Remove space from your function name! make Alphabet() must be makeAlphabet() Commented Jun 1, 2015 at 13:24

4 Answers 4

2

There are a few things wrong with this code as the comments under your post mentioned.

  1. the function name is incorrect, it has to be one word as well as the same as when you calling it to actually use the function.

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I would not use console.log inside the function! Use it only for testing purposes.
2

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(' ');

fiddle

1 Comment

Thank you for the help and sorry for bad language
0

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'.

Comments

0

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.

Comments