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: 'Santa'
}


const objectTwo = {
  lastName: 'Claus'
}


const objectCombined = Object.assign(objectOne, objectTwo);
// objectCombined is: { firstName: 'Santa', lastName: 'Claus' }

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 = ā€œWilliamā€;


console.log(newObject.speak());


// My Name is William and this is year 2019

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:ā€Williamā€,
  age:30
}


let entries = Object.entries(person);


console.log(entries);


//[ [ 'name', 'William' ], [ 'age', 30 ] ]

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"]

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"]

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: 'Batman'
}


Object.freeze(frozenObject);


frozenObject.name = 'Superman';


// frozenObject will remain equal to { name: 'Batman' }

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: 'Batman'
}


Object.seal(sealedObject);


sealedObject.name = 'Superman';
sealedObject.isBetter = true;


// sealedObject will be equal to { name: 'Superman' }

.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]

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]

.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

.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'

.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

.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

.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

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']

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]

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]

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']

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: 'Jonathan',
  city: 'Toronto'
};


const newObject = {
  ...originalObject,
  occupation: 'Chef'
}


// newObject is equal to
// { occupation: 'Chef', name: 'Jonathan', city: 'Toronto' }

Wrapping up

And there we go! 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!


Tim profile image

A little about me..

Hey, Iā€™m Tim! šŸ‘‹

Iā€™m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! šŸŽ‰