Sorting a paragraph alphabetical using javascript

952 views javascript
3

So I need to input a paragraph and sort it alphabetical and strip all commas, periods from it. so if the input is:

var nonSortedArray = ['hi', 'yo', 'whatup', 'bye', 'lol'];
var sortedArray = nonSortedArray.sort(function (a, b) {
  if (a < b) return -1;
  else if (a > b) return 1;
  return 0;
});
console.log(sortedArray); 

I thought I would be using something like this, but Im not sure how to display the paragraph because I can't have a comma after every word either.

answered question

sidenote: Array#sort doesn't return a sorted array, it sorts in place and returns this; so in some way it does return a sorted array, but nonSortedArray is also sorted now and sortedArray === nonSortedArray.

Thank you for asking your question clearly, with your expected output, and the code you’ve already tried.

Why did you delete the expected output?

2 Answers

4

To compare strings, use String.localeCompare

let str = "Sunset is the time of day when our sky meets the outer space solar winds. There are blue, pink, and purple swirls, spinning and twisting, like clouds of balloons caught in a blender.";

let result = Array.from(new Set(str.split(" "))).sort((a,b) => a.toLowerCase().localeCompare(b.toLowerCase())).join(' | ');
document.write(result);

posted this
13

You could match only word characters, filter with a Set to get unique words and sort them.

var string = 'Sunset is the time of day when our sky meets the outer space solar winds. There are blue, pink, and purple swirls, spinning and twisting, like clouds of balloons caught in a blender.',
    words = Array
        .from(new Set(string.match(/\w+/g)))
        .sort((a, b) => a.localeCompare(b))
        .join(' | ');

document.getElementById('output').innerHTML = words;
<p id="output"></p>

posted this

Have an answer?

JD

Please login first before posting an answer.