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.
![JavaScript](https://michaelsoriano.com/wp-content/uploads/2022/07/javascript.jpg)
So here are common JS snippets for data manipulation:
Find Unique Values from Array
// using SET:
let uniqueArr = [... new Set(arr)]; // MAKES NEW ARRAY
let uniqueObj = new Set(arr); // MAKES NEW OBJ
// not using SET
let uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) === pos;
})
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); //SORT BY VALUE OF .PROP IF NUMERIC
arr.sort((a,b) => (a.prop > b.prop) ? 1 : ((b.prop > a.prop) ? -1 : 0)); //SORT BY VALUE OF .PROP IF NOT NUMERIC
Sorting Objects by property value
This is when you have a Map (or a hash table), and you want to sort by key.
//obj is a map and you want to sort it by its property "sortProperty" and its a number
Object.keys(obj).sort((a, b)=> obj[a].sortProperty - obj[b].sortProperty);
//if "sortProperty" is string use:
Object.keys(obj).sort((a,b) => (a.sortProperty > b.sortProperty) ? 1 : ((b.sortProperty > a.sortProperty) ? -1 : 0));
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
2 Comments