Useful Ways to Manipulate and Process Arrays

Isaac Anzaroot
2 min readMay 11, 2021

array.filter()

Filtering an array creates a new array with all the elements of the old array that match the condition provided. This can even be used on an array of objects. Below is an example where we are filtering any objects with an ‘age’ key that have a value greater than 20.

const people = [{name: "John", age: 26}, {name: "Jane", age: 31}}, {name: "Peter", age: 18}}]const result = people.filter(person => person.age > 20)console.log(result)
// output [{name: "John", age: 26}, {name: "Jane", age: 31}]

array.splice()

The most important thing to remember is that splice() does not return a new array. It mutates the original. We can get around that by ‘spreading’ the original array to a different variable and splicing that instead. As for what splice can do, it can do a few things for us.

  • It can insert elements at a given index.
  • It can replace elements at a given index.
  • It can remove elements at a given index.

The splice method usually takes either 2 or 3 arguments. The first argument is the index to start. The second argument is the amount of elements to remove starting from the index that was passed. The third argument is the element to be inserted. (You can add multiple elements by adding more values as arguments)

const teams = ['Mets', 'Yankees', 'Expos', 'Astros', 'Cubs']// Spread the original array
const addedTeams = [...teams]
//Go to index 1, remove 0 elements, and insert 'Dodgers'
addedTeams.splice(1, 0, 'Dodgers')
console.log(addedTeams)
//output ['Mets', 'Dodgers', 'Yankees', 'Expos', 'Astros', 'Cubs']
//Replace an element in original array
//Go to index 2, remove 1 element, and insert 'Dodgers'
teams.splice(2, 1, 'Nationals')
console.log(teams)
//output ['Mets', 'Yankees', 'Nationals', 'Astros', 'Cubs']
//Remove an element from the original array
//Go to index 3, remove 1 element
teams.splice(3, 1)
console.log(teams)
//output ['Mets', 'Yankees', 'Nationals', 'Cubs']
// 'Nationals' still appears here because we mutated the original
// array before.

array.some()

The some() method returns true or false based on whether or not at least one element in the array matches the condition provided. This is useful for checking to see if an element already exists within the array.

const seasons= ['Spring', 'Summer', 'Autumn']console.log(seasons.some(season => season === 'Summer'))
//output true
console.log(seasons.some(season => season === 'Winter'))
//output false

--

--