Object & Array Methods in JavaScript

Richard Rembert - Sep 22 '22 - - Dev Community

In this article, we’ll be taking a look at some highly useful array and object methods. The eloquence of these methods will help us to write very clean and readable code — as we go about manipulating our arrays & objects.

Object.assign()

This method gives us the ability to combine objects together.

Example:

Combine two separate objects into one:

const objectOne = {
  firstName: 'Richard'
}


const objectTwo = {
  lastName: 'Rembert'
}


const objectCombined = Object.assign(objectOne, objectTwo);
// objectCombined is: { firstName: 'Richard', lastName: 'Rembert' }
Enter fullscreen mode Exit fullscreen mode

Note: You could also use the object spread syntax — which we’ll look at later in this article!

Object.create()

This method will create a new object, using an existing object as the prototype of the newly created object.

Example:

let newObject = Object.create(obj);


console.log(newObject);  
//{}


newObject.name = Richard;


console.log(newObject.speak());


// My Name is Richard and this is year 2022
Enter fullscreen mode Exit fullscreen mode

In our example, obj is the prototype from which newObject is created. So via inheritance, it can use the properties of our prototype. This is why we can use the speak() method without declaring it in newObject.

Object.entries()

Here we can create an array containing arrays of key/value pairs of an object. Essentially, it converts objects into arrays of arrays.

Example:

let person = {
  name:"Richard”,
  age:32
}


let entries = Object.entries(person);


console.log(entries);


//[ [ 'name', 'Richard' ], [ 'age', 32 ] ]
Enter fullscreen mode Exit fullscreen mode

Object.keys()

This method returns an array of the keys (or property labels) of a given object.

Example:

const seasonalColors = {
  winter: 'blue',
  spring: 'green',
  summer: 'yellow',
  fall: 'brown'
}


const types = Object.keys(seasonalColors);


// 'types' is equal to ["winter", "spring", "summer", "fall"]
Enter fullscreen mode Exit fullscreen mode

Object.values()

This method returns an array of the values of a given object.

Example:

const seasonalColors = {
  winter: 'blue',
  spring: 'green',
  summer: 'yellow',
  fall: 'brown'
}


const colors = Object.values(seasonalColors);


// 'colors' are equal to ["blue", "green", "yellow", "brown"]
Enter fullscreen mode Exit fullscreen mode

Object.freeze()

You can use this method to prevent the modification of existing object properties, or of adding new properties and values to an object. Essentially the function freezes the object from any further changes (key or values).

Example:

Freeze an object to prevent the name property from being changed.

const frozenObject = {
  name: 'Iron Man'
}


Object.freeze(frozenObject);


frozenObject.name = 'Captain America';


// frozenObject will remain equal to { name: 'Iron Man' }
Enter fullscreen mode Exit fullscreen mode

Object.seal()

This method stops any new properties from being added to an object, but it’ll still allow for existing properties to be changed.

Example:

Seal an object to prevent the isBetter property from being added.

const sealedObject = {
  name: 'Iron Man'
}


Object.seal(sealedObject);


sealedObject.name = 'Captain America';
sealedObject.isBetter = true;


// sealedObject will be equal to { name: 'Captain America' }
Enter fullscreen mode Exit fullscreen mode

.map()

With this method, we can create a new array by manipulating the values in another array. The new array is then returned.

Example:

Create an array that will multiply each number by 10:

let arr = [1,2,3,4];


let multiply10 = arr.map((val, i, arr) => {
  return val *10;
});


multiply10 = [10,20,30,40]
Enter fullscreen mode Exit fullscreen mode

Note: With .map() we just define what we want to happen & return it — no loops are required!

.filter()

Using this method we create a new array based on whether the items of an array pass a certain condition.

Example:

Create an array of lucky numbers (numbers > 3):

const allNumbers = [1, 2, 3, 4, 5, 6];


const luckyNumbers = allNumbers.filter( num => num > 3);


// luckyNumbers will be equal to [4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

.reduce()

This method will reduce all items in an array to a single value. It’s quite useful for calculating totals. And the returned value can be of any type (object, array, string, number).

Example:

Add up all the numbers in an array:

const numbers = [10, 20, 20];


const total = numbers.reduce( (accumulator, currentValue) => accumulator + currentValue);


// total will be equal to 50
Enter fullscreen mode Exit fullscreen mode

.forEach()

Using this method we can apply a function to each item in a given array.

Example:

const poets = ['Ginsberg', 'Plath', 'Yeats'];


poets.forEach( poet => console.log(poet) );


// 'Ginsberg'
// 'Plath'
// 'Yeats'
Enter fullscreen mode Exit fullscreen mode

.some()

This method checks if any item in an array passes a given condition. A good use case would be checking for user privileges.

Example:

Check if there is at least one 'teacher' in an array:

const classReady = ['student', 'student', 'teacher', 'student'];


const containsTeacher = classReady.some( element => element === 'teacher');


// containsTeacher will equal true
Enter fullscreen mode Exit fullscreen mode

.every()

This method is very similar to .some(), however, it will check if all items in an array pass a condition.

Example:

Check if all ratings are equal to or greater than 3 stars.

const ratings = [4, 5, 4, 3, 4];


const goodOverallRating = ratings.every( rating => rating >= 3 );


// goodOverallRating will equal true
Enter fullscreen mode Exit fullscreen mode

.includes()

Using this method we can check if an array contains a certain value. It’s like .some(), however, instead of looking for a condition to pass, it’ll check for a specific value in the given array.

Example:

Check if the array includes an item with the string ‘no’.

const respones = ['yes', 'maybe', 'no', 'yes'];


const includesNo = responses.includes('no');


// includesNo will equal true
Enter fullscreen mode Exit fullscreen mode

Array.from()

This method creates an array based on another array or string. However, it’s far more common to use the .map() method.

Example:

Create an array from a string:

const newArray = Array.from('abcde');


// newArray will equal ['a', 'b', 'c', 'd', 'e']
Enter fullscreen mode Exit fullscreen mode

Create an array that has double the value for each item in another array.

const doubledValues = Array.from([2, 4, 6], number => number * 2);


// doubleValues will equal [4, 8, 12]
Enter fullscreen mode Exit fullscreen mode

Array spread

We can spread arrays using the spread operator (…). This allows us to expand the elements in an array. It’s very useful when concatenating a number of arrays together.

Example:

Combine two given arrays.

const arrayOne = [1, 2, 3];
const arrayTwo = [4, 5, 6];


const combinedArrays = [...arrayOne, ...arrayTwo];


// combinedArrays is equal to [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

We can also use spread with .slice() to remove an array element without mutating the original array:

const companies = ['mercedes', 'boeing', 'starbucks', 'honda'];


const transport = [...companies.slice(0,2), ...companies.slice(3)];


// transport will equal ['mercedes', 'boeing', 'honda']
Enter fullscreen mode Exit fullscreen mode

Object spread

We can spread an object to allow for the addition of new properties and values without mutations (a new object is created). It can also be used to combine multiple objects together.

Example:

Add a new object property and value without mutating the original object:

const originalObject = {
  name: 'Richard',
  city: 'New York City'
};


const newObject = {
  ...originalObject,
  occupation: 'Software Engineer'
}


// newObject is equal to
// { occupation: 'Software Engineer', name: 'Richard', city: 'New York City' }
Enter fullscreen mode Exit fullscreen mode

Summary

We’ve looked at a number of array and object methods including: .assign(), .create(), .entries(), .keys(), .values(), .freeze(), .seal(), .map(), .filter(), .reduce(), .forEach(), .some(), .every(), .includes(), .from(), & Array/Object spread syntax.

Mastering these methods will greatly improve the readability of your code as well as give you some great go-to techniques to have ready, as you go about manipulating arrays & objects!

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .