Various Javascript Tips
Table of Contents
- Unique array in javascript
- Generate a unique global id for elements that need one
- Pre-populate an array in javascript
Unique array in javascript
And today’s code snippet is about how to get unique values from an array in JavaScript.
I have seen some versions of this snippet before, but the one I like to recommend the most is the use of a Set object alongside with the spread syntax in JavaScript.
By default, a Set is meant to store unique values and spreading it into an array is enough to give us the desired result.
const uniqueArray = arr => [...new Set(arr)]
uniqueArray(['ReactJS', 'NextJS', 'NodeJS', 'ReactJS']) // ['ReactJS', 'NextJS', 'NodeJS']
uniqueArray([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) // [1, 2, 3, 4]
Generate a unique global id for elements that need one
Examples:
- Setting
keyproperty when looping an array in ReactJS (watchout for potential performance issues if going this path!). - Setting
idattribute to DOM elements. - Cache response from endpoints that don’t provide you with an identifier.
As a curried function, it keeps a local counter variable and for every new uniqueId generated counter's value is incremented.
An optional prefix can also be sent in case you want some extra information alongside with the id.
function createUniqueId() {
let counter = 0
return (prefix = '') => {
if (prefix) {
return `${prefix}_${++counter}`
}
return `${++counter}`
}
}
const uniqueId = createUniqueId()
console.log(uniqueId()) // 1
console.log(uniqueId()) // 2
console.log(uniqueId()) // 3
console.log(uniqueId('testing')) // testing_4
Pre-populate an array in javascript
This is the second post I write about code snippets I find useful (you can check the first one here).
And today’s code snippet is how to pre-populate an array in JavaScript.
The for loop is probably one of the first choices that comes to mind when dealing with arrays or collections.
But instead, I prefer to create an array with Array.from.
If you’ve never heard of Array.from before, it accepts and array-like or an iteratable object as its first argument so we can map into it.
Once the array is created, map gives us each element in the newly created array so we can populate it with, for example, the index of each element.
function createArray(size: number) {
return Array.from({ length: size }).map((_, index) => index + 1)
}
or using the Array constructor:
function createArray(size: number) {
return Array.from(Array(size)).map((_, index) => index + 1)
}