Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- // 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']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement