首页 > 解决方案 > 使用javascript按字母顺序对段落进行排序

问题描述

所以我需要输入一个段落并按字母顺序对其进行排序,并从中删除所有逗号和句点。所以如果输入是:

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

我以为我会使用这样的东西,但我不确定如何显示该段落,因为我也不能在每个单词后面加上逗号。

标签: javascriptsorting

解决方案


您可以仅匹配单词字符,使用 a 过滤Set以获取唯一单词并对它们进行排序。

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>


推荐阅读