javascript - 如何使用打字稿对数组进行排序
问题描述
我有一个数组 ['1','2','3','4','5','6','7'] 如果用户输入 11237548, must =>1234578 我必须按数字排序并检查没有双重值
我怎样才能完成这个(逻辑)?
解决方案
您似乎有两个问题:1)如何避免重复;2)输入后如何对数组进行排序。
如何避免重复:
方法1:在添加之前检查数组的值。
const values = ['1', '2', '3', '4', '5', '6', '7']
// Simulate some input with duplicate values.
const input = '11237548'
// Split the input string into a character array.
const chars = input.split('') // ['1', '1', '2', '3', ...]
// Iterate over the characters.
chars.forEach((char) => {
// indexOf returns -1 if the value isn't in the array already.
if (values.indexOf(char) < 0) {
values.push(char)
}
})
// Result: ['1', '2', '3', '4', '5', '6', '7', '8']
// This happens to be sorted because only 8 was added
// to an already sorted array.
方法2:使用Set
类。
// Create a set with some starting values.
// A set does not add duplicates.
const values = new Set(['1', '2', '3', '4', '5', '6', '7'])
// Simulate some input with duplicate values.
const input = '11237548'
// Use Array.from to split the input characters.
const chars = Array.from(input)
// Iterate over the characters.
chars.forEach((char) => {
// The set will not add duplicates.
values.add(char)
})
// Get an array of values from the set.
const list = Array.from(values) // ['1', '2', '3', '4', '5', '6', '7', '8']
如何对数组进行排序
如果数组只包含数字,则在添加到数组之前将字符串转换为数字。
let values = [1, 2, 6, 7]
const input = '3'
// Convert the input to a number.
const num = Number(input)
if (values.indexOf(num) < 0) {
values.push(num)
}
// Values is currently unsorted: [1, 2, 6, 7, 3]
// Sort the array in place. The function will return a negative
// value when a < b, and a positive one when a > b.
values.sort(function (a, b) { return a - b }) // [1, 2, 3, 6, 7]
如果您需要数组包含字符串,请在排序时转换为数字:
let values = ['1', '2', '6', '7']
const input = '3'
if (values.indexOf(input) < 0) {
values.push(input)
}
// Values is currently unsorted: ['1', '2', '6', '7', '3']
// Sort the array in place. The function will return a negative
// value when a < b, and a positive one when a > b.
values.sort(function (a, b) { return Number(a) - Number(b) })
// Result: ['1', '2', '3', '6', '7']
注意:如果数组包含无法转换为数字的字符串,则上述内容将无法正常工作。
推荐阅读
- jquery - rails 6找不到模块'jquery'
- reactjs - 无法删除 AWS Amplify Auth
- reactjs - 在 Office Fabric UI 中最大化或最小化对话框
- apache-spark-sql - ALTER TABLE table ADD IF NOT EXISTS PARTITION (state = '34' , city = '123') 没有在 temp/local 文件夹中添加分区
- php - Wordpress 小部件错误 - 未捕获的错误:在 null 上调用成员函数 get_header_transparency()
- mysql - 从 BigQuery 中的查询中提取/获取视图中使用的表名及其各自的列
- anylogic - 如何基于 AnyLogic 模型的输出构建数据库
- python - 有没有办法恢复我的 conda 命令?
- vue.js - NuxtJS 静态站点常规选项
- logstash - Logstash 中的配置错误