Art of Array Manipulation in JavaScript.

Some easy yet powerful array methods.

As a JavaScript developer, you know that working with arrays is a critical component of your skill set. In this article, I'll be sharing the insider tricks and time-saving functions that I use on a daily basis.

Array.map()

  • map takes a callback function to modify/change each item of an array and returns a new array with the changes.
const numbers = [1, 2, 3, 4, 5]

const sqraredNumbers = numbers.map((num)=> num * num )

console.log(sqraredNumbers) // Expected Output: [1, 4, 9, 16, 25]

That means, if each item of the array is an object, we can use object properties on the item if each item of the array is an object. For example,

const person = [{name: "Peter", age: 30}, {name: "John", age: 25}, {name: "Ernest", age: 40}]

// extract names. 
const name = arr.map((obj)=> obj.name) // Output: ['Peter', 'John', 'Ernest']
// extract age
const age = arr.map(obj => obj.age) // Output: [30, 25, 40]

In the above example, we have a person array with objects as items. Each item has name and age property. Using the map function, for each item of the array, we first grabbed the name and then age.

  • To re-create an array of objects with keys and values you can do the following.
const name = ['Peter', 'John', 'Ernest'];
const age = [30, 25, 40]
const newObject = []; .

// using for loop. 

for (let i = 0; i < name.length; i++) {

const reconstructedObject = {name: name[i], age: age[i]} 
newObject.push(reconstructedObject) // push the array 

}

// using forEach 
name.forEach((element, index) => {
    const reconstructedObject = { name: element, age: age[index]}
newObject.push(reconstructedObject)
})

//Side Note:  if you want to make name key and the age it's value, //then just do this. 

name.forEach((element, index ) => newObject[element] = age[index])
// Output: [Peter: 30, John: 25, Ernest: 40]

Array.filter()

  • Filters: Returns/Outputs the new array based on the filtering criteria you provide on the callback function.
let arr = ['Kabul', 'Zalalabad', 'Interesting City', 1, 2, 3, 3, 'kabul']

let strArr = arr.filter(item => typeof item === "string") 
console.log(strArr)
// expected output: 
//['Kabul', 'Zalalabad', 'Interesting City', 'kabul']

let numArr = arr.filter(item => typeof item === "number")

// expected output: [1, 2, 3, 3]
  • In the example above, each array item is checked based on whether the item is a string or a number. Then, the filter property filters out the array based on the callback function provided.

Array.reduce().

As the name suggests, array.reduce() reduces an array to a single value. It is a powerful recursive method (a function that calls itself until the desired result is achieved). It can get complicated quickly but here is my attempt to simplify it.

  • Reduce takes a callback function with two arguments: sum and currentValue and an optional initial value.

    • sum also known as accumulator, accumulates all the values from the previous call. If the array contains numbers, reduce outputs a single value. If the array contains a string, it will join all the strings together.

    • The Initial value is optional. If provided, sum is set to the initial value. If this is not provided, sum is set to the first item of the array.

const message = ["I ", "am", "learning", "JavaScript"];

// No initial Value. So here: sum = "I". 
const reducedMessage = message.reduce((sum, currentValue)=>{
    return sum + currentValue
})
// Expected Output: I am learning Javascript

reduce example with an initial value


const message = ["I ", "am", "learning", "JavaScript"];

// With initial Value. So, sum = "Hello everyone!"
const reducedMessage = message.reduce((sum, currentValue)=>{
    return sum + currentValue
}, "Hello everyone! ")

// Expected Output: Helo everyone! I am learning Javascript

Since the sum is set to the initial value, we can set the sum to an empty array by passing an empty array in place of the initial value.

let arr = ['Kabul', 'Zalalabad', 'Interesting City', 'kabul']

// Here, sum = []. 
let lowerCasedArrays = strArr.reduce((sum, currentValue) => {
    sum.push(currentValue.toLowerCase());
    return sum
}, [])
// expected output. 
//['kabul', 'zalalabad', 'interesting city', 'kabul']
  • Explainer:

    • Above sum is set to an empty array: sum = []. That means, we can use array methods with sum. Therefore, sum.push is a valid method.

    • currentValue is each item of the array arr

    • toLowerCase() method takes a string and converts all to lower case.

    • return sum returns the array.

You could use map, forEach, for or many other methods to achieve this result instead of reduce. That might be desired since reduce can be complicated to understand, especially for beginners.

set()

  • In Javascript, Set object is a collection of unique values. So, anytime you need to filter out an array based on unique values, you would use, set.
let totallyUniqueArr = [...new Set(lowerCasedArrays)]
console.log(totallyUniqueArr)

// expected output. 
// ['kabul', 'zalalabad', 'interesting city']
  • new Set outputs the following, which is not a valid javascript object. So, I used the spread operator to spread/distribute the value of this object to the array.
new Set(["kabul", "zalalabad", "interesting city"]). 
// Expected Output: {"kabul", "zalalabad", "interesting city"}

Other simple methods.

There are multiple other methods, that are simple to understand and use.

let arr = ["Denver", "Chicago", "New York", "Houston"]
  • array.shift(): Get the first item of the array. But, it changes the length of the original array.
arr.shift() // Output: Denver
  • array.pop(): Get the last item of the array. But, it changes the length of the original array.
arr.pop() // Output: Houston
  • array.at(): Pass 0 to get the first item and pass -1 to get the last item of the array. This method does not change the length of the array.
arr.at(0) // Output: Denver
arr.at(-1) // Output: Houston

Did you find this article valuable?

Support TLDR Notes by becoming a sponsor. Any amount is appreciated!