I find myself having to look up how to do things in JavaScript. After years of doing so, I’ve realized that its pretty much a common set of techniques that look for when manipulating data. So I’ve decided to create this list. Note that this is by far not a complete list – and is one that will continue to grow.
So here are common JS snippets for data manipulation:
Find Unique Values from Array
let uniqueArr = [... new Set(arr)]; // MAKES NEW ARRAY
let uniqueObj = new Set(arr); // MAKES NEW OBJ
Sorting Flat Arrays
arr.sort((a, b) => a - b); // WILL SORT ASC
arr.sort((a, b) => b - a); // WILL SORT DESC
arr.sort() // WILL SORT STRINGS ASC
Sorting an Array of Objects
arr.sort((a, b)=> a.prop - b.prop); //WILL SORT BY VALUE OF .PROP
Find number of occurrences of an element in an Array
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const counts = {};
for (const num of arr) { //USE FOR OF
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
// WILL PRODUCE A MAP WITH ELEMENT (AS KEY), NUM OF OCCUR (AS VALUE)
Add/Subtract all numbers in an Array
let sum = arr.reduce((a, b) => a + b, 0); //ADD
let diff = arr.reduce((a, b) => a - b, 0); //SUBTRACT
Find Alphanumeric Chars from a String
'FT&abC3'.match(/^[A-Za-z0-9]+$/) //WILL RETURN [F,T,a,b,C,3]
Object keys and values
You don’t need to loop through objects to get an array of keys / values:
Object.keys(obj) // GET KEYS OF OBJECT as an array
Object.values(obj) // GET VALUES OF OBJECT as an array
Object.keys(obj).length //FIND LENGTH OF OBJECT (NOT ARRAY)
Find Largest / Smallest number in Array:
Math.max(...arr);
Math.min(...arr);
Copy Arrays by value (not by reference)
let arr1 = origArray.slice();
let arr2 = origArray.slice();
//arr1 and arr2 are complete cloned copies of origArray