Array methods in React

November 10, 2020

Array Methods in React 🤔

Let’s consider what is an array method. Simply put, an array method is a method that can be called on an array to perform an action on or with that array. Here are a few javascript array methods used in react.

.map()

This array method takes in a function that will be called on each element in a given array and it returns a new set of an array without modifying the original array. Simply put, it helps us create a new set of array based on an existing one.

The code below shows a new set of an array after using the map method to add 3 to each element in the numbers array.

const numbers = [1, 3, 5, 7]
const newNumbers = numbers.map((number) => number + 3)
// newNumbers will be equal to ['4', '6', '8', '10']

.reduce()

This is a great array method that uses an accumulator to reduce all elements in an array to a single value. It basically takes in two augments, a callback function and an initial value, performs an action, and returns a single value, the value being any type i.e. object, array, string, integer. 👉 The call back function takes in two parameters namely: accumulator and current value.

The code snippet below shows a single or the cumulated value being returned, after using the reduce method to add the accumulated value with the current value, the function is iterating over.

const numbers = [1, 2, 3, 4, 5]
const newValue = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue
)
console.log(newValue)
// newValue will return 15

It is also worthy of mentioning that there are other cool features you can use the array method to do. For more on that, check the MDN docs for example of that. Be sure to thank me later😁

.filter()

Just as it sounds, it works similar to the way the .map() method works. It filters an array based on if an element in the array, meets the condition passed in the function and then, it returns an array.

const numbers = [1, 2, 3, 4, 5, 6, 7]
const newValue = numbers.filter((number) => number >= 3)
console.log(newValue)
// newValue will return [3, 4, 5, 6, 7]

.includes()

This method simply checks if an element exists in a given array and returns a boolean(true or false). Do note that there are some constraints with regards to the data types that the include method can check for. This is because of the way Javascript treats objects and primitive types.

const numbers = [1, 2, 3, 4, 5]
const newValue = numbers.includes(3)
console.log(newValue)
// newValue will return true

.find()

This method takes in a function that checks for a specific element in an array and returns the very first occurrence of the condition.

const numbers = [1, 2, 3, 4]
const newValue = numbers.find((number) => number > 3)
console.log(newValue)
// newValue will return 4

.forEach()

Applies a function on each item in an array.

Log each array item to the console

const emotions = ['happy', 'sad', 'angry']
emotions.forEach((emotion) => console.log(emotion))
// Will log the following:
// 'happy'
// 'sad'
// 'angry'

👉 counting duplicate values

uniqueCount = [
  '1',
  '2',
  '3',
  '4',
  '4',
  '5',
  '1',
  '2',
  '3',
  '6',
  '8',
  '9',
  '9',
  '9',
  '5',
  '8',
]
let count = {}
uniqueCount.forEach(function (i) {
  count[i] = (count[i] || 0) + 1
})
console.log(count)

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

👉 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 will be equal to true

.every()

Similar to .some(), but checks if all items in an array pass a condition. Example 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 will be equal to 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. I’m not too sure why someone would use this over the .map() method.

Create an array from a string.

const newArray = Array.from('hello')
// newArray will be equal to ['h', 'e', 'l', 'l', 'o']

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 be equal to [4, 8, 12]

Object.values()

Return an array of the values of an object.

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.

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.

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

Combine two arrays.
const spreadableOne = [1, 2, 3, 4];
const spreadableTwo = [5, 6, 7, 8];

const combined = [...spreadableOne, ...spreadableTwo];
// combined will be equal to [1, 2, 3, 4, 5, 6, 7, 8]

Remove an array element without mutating the original array.

const animals = ['squirrel', 'tiger', 'lion', 'horse', 'rabbit']
const mammals = [...animals.slice(0, 3), ...animals.slice(4)]
// mammals will be equal to ['squirrel', 'tiger', 'lion', 'rabbit']

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.

👉 Add a new object property and value without mutating the original object.

const spreadableObject = {
  name: 'Irene',
  phone: 'iPhone',
}

const newObject = {
  ...spreadableObject,
  carModel: 'Suzuki',
}
// newObject will be equal to
// { carModel: 'Suzuki', name: 'Irene', phone: 'iPhone' }

Function Rest

👉 Functions can use the rest parameter syntax to accept any number of arguments as an array.

Display the array of passed arguments.
function displayArgumentsArray(...theArguments) {
  console.log(theArguments);
}

displayArgumentsArray('hi', 'there', 'bud');
// Will print ['hi', 'there', 'bud']

Object.freeze()

Prevents you from modifying existing object properties or adding new properties and values to an object. Actually const allows to modify an object.

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

const frozenObject = {
  name: 'Irene',
}

Object.freeze(frozenObject)

frozenObject.name = 'Mary'
// frozenObject will be equal to { name: 'Irene' }

Object.seal()

Stops any new properties from being added to an object, but still allows for existing properties to be changed.

👉 Seal an object to prevent the wearsWatch property from being added.

const sealedObject = {
  name: 'Irene',
}

Object.seal(sealedObject)

sealedObject.name = 'Mary'
sealedObject.wearsWatch = true
// sealedObject will be equal to { name: 'Mary' }

Object.assign()

Allows for objects to be combined together. This method is not really needed because you can use the object spread syntax instead. Like the object spread operator, Object.assign() does not do deep cloning. Lodash is your best friend when it comes to deep cloning objects.

👉 Combine two objects into one.

const firstObject = {
  firstName: 'Irene',
}

const secondObject = {
  lastName: 'Simpson',
}

const combinedObject = Object.assign(firstObject, secondObject)
// combinedObject will be equal to { firstName: 'Irene', lastName: 'Simpson' }

Math.floor() / Math.random()

chose random number from array react

let items = ['Yes', 'No', 'Maybe']
let item = items[Math.floor(Math.random() * items.length)]

👉 Pick a random element

let myArray = ['Apples', 'Bananas', 'Pears']

let randomItem = myArray[Math.floor(Math.random() * myArray.length)]

👉 get a random string from a array

  • a random string
const randomElement = array[Math.floor(Math.random() * array.length)]
let groceries = ['milk', 'coriander', 'cucumber', 'eggplant']
let mygroceries = groceries[Math.floor(Math.random() * groceries.length)]
console.log(mygroceries) //This gives you any string from groceries
array.sort(() => Math.random() - Math.random()).slice(0, n)
let items = ['Yes', 'No', 'Maybe']
let item = items[Math.floor(Math.random() * items.length)]

Read more about JavaScript Array class

🐘 🌴

Up next