Return an array of unique values and add a value using new Set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Data array | |
const data = [{key: 'value 1'}, {key: 'value 1'}, {key: 'value 2'}, {key: 'value 3'}] | |
// Extended version | |
// 1. get all values | |
// 2. create a new Set and get unique values | |
// 3. create a new array and add a new value | |
const values = data.map(value => value.key) // ['value 1', 'value 1', 'value 2', 'value 3'] | |
const uniqueValues = new Set(values) // {'value 1', 'value 2', 'value 3'} | |
const newUniqueValues = [...uniqueValues, 'value 4'] // ['value 1', 'value 2', 'value 3', 'value 4'] | |
// Short Version (all-in-one) | |
const newerUniqueValues = [...new Set(data.map(value => value.key)), 'value 4'] // ['value 1', 'value 2', 'value 3', 'value 4'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment