javascript - 使用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);
我以为我会使用这样的东西,但我不确定如何显示该段落,因为我也不能在每个单词后面加上逗号。
解决方案
您可以仅匹配单词字符,使用 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>
推荐阅读
- ios - 如何在溢出屏幕的 SwiftUI 中制作无限宽度的视图?
- python - 尝试使用 django 运行服务器时如何修复错误?
- flutter - Dio 4.0.0 (Dart) 中奇怪的 BaseOptions 问题
- python - 获取属于特定类的数据子集
- java - 从动态字符串中获取运算符之前的子字符串
- python - 为什么 discord 不返回 COVID19 结果数据?
- amazon-web-services - 创建 AWS 弹性 Beanstalk Spring 实例并将其分配给 VPC
- hibernate - reddison hibernate 作为二级缓存的问题
- java - 短期 Java CLI 应用程序的性能
- html - 如何让一件物品在另一件物品开始收缩之前完全收缩?