Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. const values = ['1', '2', '3', '4', '5', '6', '7']
  2.  
  3. // Simulate some input with duplicate values.
  4. const input = '11237548'
  5.  
  6. // Split the input string into a character array.
  7. const chars = input.split('') // ['1', '1', '2', '3', ...]
  8.  
  9. // Iterate over the characters.
  10. chars.forEach((char) => {
  11. // indexOf returns -1 if the value isn't in the array already.
  12. if (values.indexOf(char) < 0) {
  13. values.push(char)
  14. }
  15. })
  16.  
  17. // Result: ['1', '2', '3', '4', '5', '6', '7', '8']
  18. // This happens to be sorted because only 8 was added
  19. // to an already sorted array.
  20.  
  21. // Create a set with some starting values.
  22. // A set does not add duplicates.
  23. const values = new Set(['1', '2', '3', '4', '5', '6', '7'])
  24.  
  25. // Simulate some input with duplicate values.
  26. const input = '11237548'
  27.  
  28. // Use Array.from to split the input characters.
  29. const chars = Array.from(input)
  30.  
  31. // Iterate over the characters.
  32. chars.forEach((char) => {
  33. // The set will not add duplicates.
  34. values.add(char)
  35. })
  36.  
  37. // Get an array of values from the set.
  38. const list = Array.from(values) // ['1', '2', '3', '4', '5', '6', '7', '8']
  39.  
  40. let values = [1, 2, 6, 7]
  41.  
  42. const input = '3'
  43.  
  44. // Convert the input to a number.
  45. const num = Number(input)
  46.  
  47. if (values.indexOf(num) < 0) {
  48. values.push(num)
  49. }
  50.  
  51. // Values is currently unsorted: [1, 2, 6, 7, 3]
  52.  
  53. // Sort the array in place. The function will return a negative
  54. // value when a < b, and a positive one when a > b.
  55. values.sort(function (a, b) { return a - b }) // [1, 2, 3, 6, 7]
  56.  
  57. let values = ['1', '2', '6', '7']
  58.  
  59. const input = '3'
  60.  
  61. if (values.indexOf(input) < 0) {
  62. values.push(input)
  63. }
  64.  
  65. // Values is currently unsorted: ['1', '2', '6', '7', '3']
  66.  
  67. // Sort the array in place. The function will return a negative
  68. // value when a < b, and a positive one when a > b.
  69. values.sort(function (a, b) { return Number(a) - Number(b) })
  70. // Result: ['1', '2', '3', '6', '7']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement