Methods for array and objects in JavaScript
Javascript has a vast library of methods for manipulating arrays and objects. Using them makes code more readable because:
- Their names resemble verbs
- Reduces the amount of code
For example, here’s a for loop that’s a staple of many Javascript 101 courses:
const input = [1,2,3,4,5]const output = []
for(let i=0; i<input.length; i++){
output[i] = input[i]*5
}console.log(output);
Here’s the same but from using map():
const input = [1,2,3,4,5]console.log(input.map((item)=> item*5));
Both produce the same result, but using map() results in less code. Given time, you’d also gain a sense of what to expect upon seeing map() which aids your ability to read code. Having less code also helps the next person who has to read and build on top of your code: All code is meant to be read after all.
I understand if methods don’t come immediately to new coders. Back when I started coding, I had a tendency to just write. Now, I first check if the library has something that can do the same. It’s a good habit that’s practically mandatory in practice. The effort pays off though: Wherever JavaScript (JS) or TypeScript (TS) is used, you can reapply the same methods.
Here’s methods I frequently use. Some are from Lodash:
Array and object methods
Tip: Many array methods also apply to strings since strings are technically arrays in JS.
Native to JavaScript:
- Work on values in an array: map, reduce, filter
Git gud with these, they’re used everywhere. Here’s what they can do together:
const input= [1,2,3,100,200,300]const result = input
// Multiply all input[] items by 2
.map((item)=> item*2)
// Remove all items of value >100
.filter((item)=> item>100)
// Add together all items
.reduce((item, currentTotal)=> item+currentTotal, 0)console.log(result) // 12
- Insert values into arrays:
array.push to insert at end of array, array.concat to do the same and also return the result - Remove values from arrays:
array.slice to grab a segment of an array, array.splice to remove and/or insert new values into an array - Get index of first item in array…
That matches the given criteria: array.findIndex
That matches the given value: array.indexOf - Find first item in array matching given criteria: array.find
- Sort items in array: array.sort
- Get object keys and values as an array: Object.keys, Object.values
Returns object keys/values an array. Useful for manipulation by iteration:
const data = {a:1, b:2, c:3}for(const key of Object.keys(data)){
if(data[key]=== 2) console.log(`Field ${key} has value "2"`)
}
- Speaking of iteration, get familiar with for-of and for-in loops. They’re more readable and for-in can work directly on an object. The only catch is they do not provide a variable that stores the current iteration.
Using the example above with a for-in loop:
const data = {a:1, b:2, c:3}for(const key in data){
if(data[key]=== 2) console.log(`Field ${key} has value "2"`)
}
- Spread syntax. A fast way to combine objects/arrays:
const array1 = [0,1,2]
const array2 = [3,4,5]console.log([...array1, ...array2]) // [0,1,2,3,4,5]const object1 = {a:1, b:2, c:3}
const object2 = {d:4, e:5}console.log({...object1, ...object2}) // {a:1, b:2, c:3, d:4, e:5}
Lodash
Lodash is not in as much use as before because JS-native methods got better. Radash is a promising challenger. Here’s some I still find useful:
- get: Get a value at a given path in an object. It’s helpful when dot notation gets too tedious and when the same path is used elsewhere because it can be shared as a string
- forIn: Works like a for-in loop. Most useful when chaining lodash methods
- groupBy : Group together array elements matching a given criteria
A handy tool when working with arrays containing objects. It allows putting together objects that have the same value at a given path:
const input = [
{item: 1, earnings: 5, soldBy: {name:"Jon", id: 6987}},
{item: 3, earnings: 15, soldBy: {name:"Jan", id: 1987}},
{item: 1, earnings: 3, soldBy: {name:"Jon", id: 6987}},
{item: 2, earnings: 22, soldBy: {name:"Jon", id: 6987}},
{item: 4, earnings: 8, soldBy: {name:"Jim", id: 1234}},
{item: 4, earnings: 16, soldBy: {name:"Jim", id: 1234}}
]const output = _.groupBy(input, "soldBy.name"))// Value of output:
{
"Jon": [
{
"item": 1,
"earnings": 5,
"soldBy": {
"name": "Jon",
"id": 6987
}
},
{
"item": 1,
"earnings": 3,
"soldBy": {
"name": "Jon",
"id": 6987
}
},
{
"item": 2,
"earnings": 22,
"soldBy": {
"name": "Jon",
"id": 6987
}
}
],
"Jan": [
{
"item": 3,
"earnings": 15,
"soldBy": {
"name": "Jan",
"id": 1987
}
}
],
"Jim": [
{
"item": 4,
"earnings": 8,
"soldBy": {
"name": "Jim",
"id": 1234
}
},
{
"item": 4,
"earnings": 16,
"soldBy": {
"name": "Jim",
"id": 1234
}
}
]
}