1. Filter unique values
The Set object type was introduced in ES6. Together with the expansion operation... together, we can use it to create a new array with only unique values.
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]
Before ES6, isolating unique values would involve much more code than this.
This technique is suitable for arrays containing basic types: undefined, null, boolean, string and number. (If you have an array containing objects, functions, or other arrays, you need a different approach!)
2. Convert to Boolean
const isTrue = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"
3. Convert to string
const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"
4. Convert to numbers
Use the addition operator + to quickly achieve the opposite effect.
let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"
This can also be used to convert boolean values to numbers as shown below
console.log(+true); // Return: 1
console.log(+false); // Return: 0
5. Array truncation
If you want to delete values from the end of the array, there is a faster method than using splice().
For example, if you know the size of the original array, you can redefine its length property like this
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]
This is a particularly concise solution. However, I found that the slice() method runs faster. If speed is your main goal, consider using:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]
6. Get the last item in the array
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]
7. Format JSON code
Finally, you may have used JSON.stringify before, but did you realize that it can also help you indent JSON?
The stringify() method has two optional parameters: a replacer function, which can be used to filter the displayed JSON and a space value
console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
// "alpha": A,
// "beta": B
// }'