The author of the article, the translation of which we are publishing today, says that her idea was suggested to him by one of the episodes of the
Syntax FM podcast, which gave an overview of the useful methods of objects and arrays in JavaScript. These methods help developers write clean and readable code. Their use reduces the need for third-party libraries like
Lodash .

Array.prototype.filter ()
The
Array.prototype.filter () method creates a new array in which only those elements of the original array that match the specified condition fall.
▍Example
On the basis of an array containing information about students, we will create a new array in which only records of those students whose age allows them to buy alcohol will fall.
const studentsAge = [17, 16, 18, 19, 21, 17]; const ableToDrink = studentsAge.filter( age => age > 18 );
Array.prototype.map ()
The
Array.prototype.map () method allows you to create a new array based on somehow processed values from another array. This method is great for modifying data, because it does not make changes to the original array, it is often used in React.
▍Example
Let's create, on the basis of a numeric array, a new array, at the beginning of each element of which the
$
sign will be placed.
const numbers = [2, 3, 4, 5]; const dollars = numbers.map( number => '$' + number);
Array.prototype.reduce ()
The
Array.prototype.reduce () method is often undeservedly overlooked. It allows you to reduce the array to a single value that accumulates in the element-receiver. The value returned by this method can be of any type. For example, it can be an object, an array, a string, or a number.
▍Example
We use the
.reduce()
method to get the sum of the elements of a numeric array.
const numbers = [5, 10, 15]; const total = numbers.reduce( (accumulator, currentValue) => accumulator + currentValue);
In fact, this method can be used in many interesting ways. Examples can be found in the
MDN documentation . In particular, we are talking about expanding arrays consisting of arrays, about grouping objects by properties, and about removing duplicate elements from arrays.
Array.prototype.forEach ()
The
Array.prototype.forEach () method applies the function passed to it to each element of the array.
▍Example
Here's how to output each element of the array to the console using the
.forEach()
method.
const emotions = ['happy', 'sad', 'angry']; emotions.forEach( emotion => console.log(emotion) ); // : // 'happy' // 'sad' // 'angry'
Array.prototype.some ()
The
Array.prototype.some () method checks whether at least one array element meets the condition specified by the function passed to it. This method, for example, is able to show itself well in solving the task of checking the user's authority. It can be considered as an analogue of the previously considered
.forEach()
, with the difference that, when applied, using the function that is passed to it, you can perform certain actions on the array elements until this function returns the true value, then interrupt processing.
▍Example
Check if there is at least one
admin
string in the array.
const userPrivileges = ['user', 'user', 'user', 'admin']; const containsAdmin = userPrivileges.some( element => element === 'admin');
Array.prototype.every ()
The
Array.prototype.every () method is similar to the above described
.some()
method, but it returns
true
only if all the elements of the array meet the condition specified by the function passed to this method.
▍Example
Check if all the scores stored in the array are equal to or greater than 3.
const ratings = [3, 5, 4, 3, 5]; const goodOverallRating = ratings.every( rating => rating >= 3 );
Array.prototype.includes ()
The
Array.prototype.includes () method allows you to find out if an array contains a specified value. It is similar to the
.some()
method, but it does not check whether the array elements correspond to a certain condition, but the presence in the array of the value specified when it is called.
▍Example
Check if there is a
waldo
string element in the array:
const names = ['sophie', 'george', 'waldo', 'stephen', 'henry']; const includesWaldo = names.includes('waldo');
Array.from ()
The static method
Array.from () allows you to create arrays based on other arrays or strings. This method, if necessary, can be passed a function to perform mapping, which allows you to affect the data that falls into the new array. In fact, a special method is provided for performing mapping -
Array.prototype.map () , so it’s not quite clear why anyone would need this feature of the
Array.from()
method.
▍Example
Create an array based on the string.
const newArray = Array.from('hello'); // newArray ['h', 'e', 'l', 'l', 'o']
Create an array containing the doubled values of the elements of the original numeric array.
const doubledValues = Array.from([2, 4, 6], number => number * 2);
Object.values ()
The
Object.values () method returns an array of property values of the object passed to it.
▍Example
Let's form an array of the object's property values.
const icecreamColors = { chocolate: 'brown', vanilla: 'white', strawberry: 'red', } const colors = Object.values(icecreamColors); // colors ["brown", "white", "red"]
Object.keys ()
The
Object.keys () method returns an array consisting of the object property names (keys).
▍Example
Let's form an array of object property names.
const icecreamColors = { chocolate: 'brown', vanilla: 'white', strawberry: 'red', } const types = Object.keys(icecreamColors); // types: ["chocolate", "vanilla", "strawberry"]
Object.entries ()
The
Object.entries () method returns, processing the object passed to it, an array containing arrays representing pairs of the form
[, ]
representing the names of properties and the values of these properties.
▍Example
Let us form an array containing, for the object of interest to us, data about the names of properties and their values.
const weather = { rain: 0, temperature: 24, humidity: 33, } const entries = Object.entries(weather); // entries // [['rain', 0], ['temperature', 24], ['humidity', 33]]
Extension operator and arrays
The extension operator (
spread operator , ...), as applied to arrays, allows you to expand them, extracting their elements from them. This operator is useful, for example, when you need to merge several arrays. In addition, its use eliminates the need to use the
.splice()
method if you need to remove some elements from the array, since it can be combined with the
.slice()
method, which allows you to avoid changing the original array.
▍Example
Combine two arrays.
const spreadableOne = [1, 2, 3, 4]; const spreadableTwo = [5, 6, 7, 8]; const combined = [...spreadableOne, ...spreadableTwo];
We create a new array, which is the original array from which the element is removed. In this case, the original array should not change.
const animals = ['squirrel', 'bear', 'deer', 'salmon', 'rat']; const mammals = [...animals.slice(0,3), ...animals.slice(4)]; // mammals : ['squirrel', 'bear', 'deer', 'rat']
Extension operator and objects
Applying an extension operator to objects allows you to add new properties and values to them without changing the original objects (that is, as a result of such operations, new objects are created). In addition, this statement can be used to combine objects. It is worth noting that the extension operator applied to the object does not affect the objects nested in it.
▍Example
Create a new object by adding a new property to the original object, without changing the original object.
const spreadableObject = { name: 'Robert', phone: 'iPhone' }; const newObject = { ...spreadableObject, carModel: 'Volkswagen' }
Syntax of the remaining function parameters
When working with functions, you can use the
syntax of the remaining parameters in order to organize the reception of any number of arguments in the form of an array.
▍Example
Print an array containing the arguments passed to the function.
function displayArgumentsArray(...theArguments) { console.log(theArguments); } displayArgumentsArray('hi', 'there', 'bud');
Object.freeze ()
The
Object.freeze () method “freezes” an object, preventing changes to the existing properties of this object or the addition of new properties and values to the object. There is an erroneous opinion that this method is similar to declaring objects using the
const
keyword, however, it is possible to modify constant objects.
▍Example
“Freeze” the object, after which we will try to change its property and make sure that this cannot be done.
const frozenObject = { name: 'Robert' } Object.freeze(frozenObject); frozenObject.name = 'Henry'; // frozenObject , { name: 'Robert' }
Object.seal ()
The
Object.seal () method allows you to "seal" the object, preventing the addition of new properties. In this case, the existing properties can be changed.
▍Example
“We seal” the object, which will not allow adding a new property to it, but will leave the possibility to change existing properties.
const sealedObject = { name: 'Robert' } Object.seal(sealedObject); sealedObject.name = 'Bob'; sealedObject.wearsWatch = true; // sealedObject : { name: 'Bob' }
Object.assign ()
The
Object.assign () method allows you to combine objects by copying properties from one object to another. In fact, the same effect can be achieved with the help of the expansion operator described above; therefore, it is quite possible to do without this method. It should be noted that this method, like the extension operator, does not perform deep object cloning. If you need a ready-made tool for deep cloning of objects, take a look at the
Lodash library
tools .
▍Example
Create one of two objects.
const firstObject = { firstName: 'Robert' } const secondObject = { lastName: 'Cooper' } const combinedObject = Object.assign(firstObject, secondObject);
Results
In this article, we talked about the useful methods of arrays and objects in JavaScript. Many of the methods discussed here return new arrays or objects. This makes it possible to combine them, combining them into chains. These methods do not modify the source data, which is especially important in React development. In addition, the use of these methods, in the overwhelming majority of cases, makes it possible to abandon cycles like
for
and
while
.
Dear readers! What methods of arrays and objects in JavaScript do you use most often?
