首页 > 解决方案 > 如何使用打字稿对数组进行排序

问题描述

我有一个数组 ['1','2','3','4','5','6','7'] 如果用户输入 11237548, must =>1234578 我必须按数字排序并检查没有双重值

我怎样才能完成这个(逻辑)?

标签: javascripttypescript

解决方案


您似乎有两个问题: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']

注意:如果数组包含无法转换为数字的字符串,则上述内容将无法正常工作。


推荐阅读