![](https://www.awebo.org/wp-content/uploads/2015/08/javascript-mexico.jpg)
Javascript Array and Object Methods
All methods are chainable, meaning tehy can be used in combination with one another and they also don´t mutate data, which is especially important when working with React. With all this array and object methods you’ll find maybe that you never have to reach for a for or while loop ever again.
.filter()
Creates a new array based on whether the items of an array pass a certain condition.
Ex. Create an array of student ages that meet legal drinking age:
const studentsAge = [17, 16, 18, 19, 21, 45, 23, 12];
const ableToDrink = studentsAge.filter(age => age > 18);
// ableToDrink will equal to [18, 19, 21, 45, 23]
.map()
Creates a new array by manipulating the values in another array. Great for data manipulation and it is often used in React due it’s immutable methods.
Ex. Create an array that adds a $ to the beginning of each number:
const numbers = [2, 3, 4, 5];
const pesos = numbers.map(number => '$' + number);
// pesos will be equal to ['$ 2','$ 3', '$ 4', '$ 5'];
.reduce()
This often overlooked method uses an accumulator to reduce all items in an array to a single value. Great for calculating totals. The returned value can be of any type (i.e. object, array, string, integer).
Ex. Add up the integers in an array:
const numbers = [5, 10, 15];
const total = numbers.reduce((accumulator, currentValue) =>
accumulator + currentValue
);
// total equals 30
There are some really cool use cases for .reduce() outlined in the MDN docs that provide examples on how to do things likes flattening an array of arrays, grouping objects by a property, and removing duplicate items in array.
.forEach()
Applies a function on each item in an array.
Ex. Log each item to the console:
const emotions = ['happy', 'sad', 'angry'];
emotions.foreach(emotion => console.log(emotion));
//happy
//sad
//angry
.some()
Checks if any item in an array passes the condition. A good use case would be checking for user privileges. It can also be used similarly to a foreach() where you would perform an action on each array item and break out of the loop once a truthy value is returned.
Ex. Check if there is at least one ‘admin’ in an array.
const userPrivileges = ['user','user','user','admin'];
const containsAdmin = userPrivileges.some(element => element === 'admin');
//containsAdmin is equal to true
.every()
Similar to .some(), but checks if all items in an array pass a condition.
Ex. Check if all ratings are equal to or greater than 3 stars.
const ratings = [3, 5, 4, 3, 5];
const goodOverallRating = ratings.every(rating => rating >= 3);
// goodOverallRating is equal to true
.includes()
Checks if an array contains a certain value. It`s similar to .some(), but instead of looking for a condition to pass, it looks if the array contains a specific value.
Ex. Check if the array includes an item with the string ‘waldo’.
const names = ['sophie','george','waldo','stephen','henry'];
cons includesWaldo = names.include('waldo');
// True
Array.from()
This is a static method that creates an array based on another array or string. You can also pass a map callback function as an argument to further shape the data in the new array.
Ex. Create an array from a string:
const newArray = Array.from('hello');
// newArray will be equal to ['h','e','l','l','o']
Ex. Create an array that has double the value for each item in another array:
const doubleValues = Array.from([2,4,6], number => number * 2);
// doubleValues will be equal to [4,8,12]
Object.values()
Return an array of the values of an object.
Ex.
const icecreamColors = {
chocolate: 'Brown',
vanilla: 'White',
strawberry: 'Red'
}
const colors = Object.values(icecreamColors);
// colors will be equal to ['Brown','White','Red']
Object.keys()
Return an array of the keys of an object.
Ex.
const icecreamColors = {
chocolate: 'Brown',
vanilla: 'White',
strawberry: 'Red'
}
const types = Object.keys(icecreamColors);
// types will be equal to ['chocolate', 'vanilla', 'strawberry']
Object.entries()
Creates an array which contains arrays of key/value pairs of an object.
Ex.
const weather = {
rain: 0,
temperature: 24,
humidity: 33
}
const entries = Object.entries(weather);
// entries will be equal to
// [['rain', 0], ['temperature', 24], ['humidity', 33]]
Array spread
Spreading arrays using the spread operator (…) allows you to expand the elements in an array. It’s useful when concatenating a bunch of arrays together. It’s also a good way to avoid using splice() method when looking to remove certain elements from an array because it can be combined with the slice() method to prevent direct mutation of an array.
Ex. Combine two arrays
const spreadableOne = [1, 2, 3, 4];
const spreadableTwo = [5, 6, 7, 8];
const combined = [...spreadableOne, ...spreadableTwo];
// combined equals [1, 2, 3, 4, 5, 6, 7, 8]
Ex. Remove an array element without mutating the original array
const animals = ['squirrel','bear','deer','salmon','rat'];
const mammals = [...animals.slice(0,3), ...animals.slice(4)];
// mammals will be equal to ['squirrel','bear','deer','rat'];
object spread
Spreading an object allows for the addition of new properties and values to an object without mutations (i.e. a new object is created) and it can also be used to combine multiple objects together. It should be noted that spreading objects does not do nested copying.
Ex. Add a new object property and value without mutating the original object.
const spreadableObject = {
name: 'Robert',
phone: 'iphone'
}
const newObject = {
...spreadableObject,
carModel: 'Volkswagen'
}
// newObject will be equal to
// {carModel: 'Volkswagen', name: 'Robert', phone: 'iphone'}
Function Rest
Functions can use the rest parameter syntax to accept any number of arguments as an array.
Ex. Display the array of passed arguments.
function displayArgumentsArray(...theArguments){
console.log(theArguments);
}
displayArgumentsArray('hi','there','friend');
// Prints ['hi','there','friend']
Object.freeze()
Prevents you from modifying existing objects properties or adding new properties and values to an object. It’s often what people think const does, however const allows you to modify an object.
Ex. freeze an object to prevent the name property from being changed.
const frozenObject = {
name: 'Robert'
}
Object.freeze(frozenObject);
frozenObject.name = 'Henry';
// frozenObject will be { name: 'Robert'}
Object.seal()
Stops any new properties from being added to an object, but still allows for existing properties to be changed.
Ex. Seal an object to prevent the wearsWatch property from being added.
const sealedObject = {
name: 'Robert'
}
Object.seal(sealedObject);
sealedObject.name = 'Bob';
sealedObject.wearsWatch = true;
// sealedObject will be { name: 'Bob'}
Have Fun!!!
give loveJavascript Array and Object Methods 306
Javascript Array and Object Methods
2 comments