Object & Array Methods in JavaScript
Tags: productivity, programming, javascript, webdev
Published: 2022-09-22 20:16:56

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:
```js
const objectOne = {
  firstName: 'Richard'
}


const objectTwo = {
  lastName: 'Rembert'
}


const objectCombined = Object.assign(objectOne, objectTwo);
// objectCombined is: { firstName: 'Richard', lastName: 'Rembert' }
```
**_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:_**
```js
let newObject = Object.create(obj);


console.log(newObject);  
//{}


newObject.name = “Richard”;


console.log(newObject.speak());


// My Name is Richard and this is year 2022
```
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:_**
```js
let person = {
  name:"Richard”,
  age:32
}


let entries = Object.entries(person);


console.log(entries);


//[ [ 'name', 'Richard' ], [ 'age', 32 ] ]
```

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

**_Example:_**
```js
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:_**
```js
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.
```js
const frozenObject = {
  name: 'Iron Man'
}


Object.freeze(frozenObject);


frozenObject.name = 'Captain America';


// frozenObject will remain equal to { name: 'Iron Man' }
```

## 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.
```js
const sealedObject = {
  name: 'Iron Man'
}


Object.seal(sealedObject);


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


// sealedObject will be equal to { name: 'Captain America' }
```

## .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_:
```js
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):
```js
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:
```js
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:_**
```js
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:
```js
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.
```js
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’`.
```js
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:
```js
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.
```js
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.
```js
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_:
```js
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:
```js
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' }
```

## 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](https://twitter.com/RembertDesigns) where I post daily about Tech related things!
![Buy Me A Coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijinng8k7bf23v0o6gkj.png) If you enjoyed this article & would like to leave a tip — click [here](https://www.buymeacoffee.com/rembertdesigns)

### 🌎 Let's Connect

- [Portfolio](https://www.rembertdesigns.co/)

- [Twitter](https://twitter.com/RembertDesigns)

- [LinkedIn](https://www.linkedin.com/in/rrembert/)

- [Hashnode](https://rembertdesigns.hashnode.dev/)

- [Devto](https://dev.to/rembertdesigns)

- [Medium](https://medium.com/@rembertdesigns)

- [Github](https://github.com/rembertdesigns)

- [Codepen](https://codepen.io/rembertdesigns)