How Data Transformations works in Javascript ?

Data transformations in JavaScript involve manipulating and changing the structure or content of data. There are various techniques and functions available in JavaScript to perform these transformations. Here are some common approaches and methods:

  1. Array Methods:
    JavaScript arrays provide several built-in methods for transforming data:
  • map: Creates a new array by applying a function to each element in the original array. const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); // doubled: [2, 4, 6, 8]
  • filter: Creates a new array with elements that pass a certain condition. const numbers = [1, 2, 3, 4]; const evens = numbers.filter(num => num % 2 === 0); // evens: [2, 4]
  • reduce: Reduces an array to a single value by applying a function to each element. const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, num) => acc + num, 0); // sum: 10
  1. Spread Operator:
    The spread operator (...) is useful for creating shallow copies of arrays and objects or combining them.
   const arr1 = [1, 2, 3];
   const arr2 = [...arr1, 4, 5];
   // arr2: [1, 2, 3, 4, 5]
  1. Object Destructuring:
    Destructuring allows you to extract values from objects and arrays, making it easier to work with specific parts of the data.
   const person = { name: 'John', age: 30 };
   const { name, age } = person;
   // name: 'John', age: 30
  1. Functional Programming:
    Concepts from functional programming, such as pure functions and immutability, can be applied to facilitate data transformations. Libraries like Lodash provide utility functions for common data manipulation tasks.
   const lodash = require('lodash');

   const numbers = [1, 2, 3, 4];
   const squared = lodash.map(numbers, num => num ** 2);
   // squared: [1, 4, 9, 16]
  1. Promises and Asynchronous Operations:
    When dealing with asynchronous code, Promises and async/await are commonly used for transforming data received from asynchronous operations.
   function fetchData() {
     return new Promise((resolve) => {
       setTimeout(() => resolve({ data: 'Some data' }), 1000);
     });
   }

   async function processData() {
     const result = await fetchData();
     console.log(result.data);
   }

   processData();

These are just a few examples, and the appropriate method depends on the specific transformation needed and the nature of the data. JavaScript provides a rich set of tools for working with data in a flexible and expressive way.

Functional programming is all about transforming data from one form to another. We will produce transformed copies using functions. These functions make our code less imperative and thus reduce complexity

Data Transformations two core functions are

  • Array.map
  • Array.reduce

join() method in javascript

const schools = [
 "Yorktown",
 "Washington & Lee",
 "Wakefield"
]
console.log( schools.join(", ") ) 
// "Yorktown, Washington & Lee, Wakefield"

join is a built-in JavaScript array method that we can use to extract a delimited string from our array. The original array is still intact; join simply provides a different take on it

Array.filter:

Array.filter is a built-in JavaScript function that produces a new array from a source array. This function takes a predicate as its only argument. A predicate is a function that always returns a Boolean value: true or false. Array.filter invokes this predicate once for every item in the array. That item is passed to the predicate as an argument and the return value is used to decide if that item shall be added to the new array

Example of Array.filter:

If we wanted to create a function that creates a new array of the schools that begin with the letter “W”, we could use the Array.filter method

const wSchools = schools.filter(school => school[0] === "W")
console.log( wSchools ) // ["Washington & Lee", "Wakefield"]

When it is time to remove an item from an array we should use Array.filter over Array.pop or Array.splice because Array.filter is immutable

Array.map:

Array.map method takes a function as its argument. This function will be invoked once for every item in the array, and whatever it returns will be added to the new array:

Example

const highSchools = schools.map(school => `${school} High School`)
console.log(highSchools.join("\n"))
// Yorktown High School
// Washington & Lee High School
// Wakefield High School
console.log(schools.join("\n"))
// Yorktown
// Washington & Lee
// Wakefield

The map function can produce an array of objects, values, arrays, other functions any JavaScript type

Object.keys is a method that can be used to return an array of keys from an object.

const highSchools = schools.map(school => ({ name: school }))
console.log( highSchools )
// [
// { name: "Yorktown" },
// { name: "Washington & Lee" },
// { name: "Wakefield" }
//]

An Example to change just one object of array with map

let schools = [
 { name: "Yorktown"},
 { name: "Stratford" },
 { name: "Washington & Lee"},
 { name: "Wakefield"}
]
let updatedSchools = editName("Stratford", "HB Woodlawn", schools)
console.log( updatedSchools[1] ) // { name: "HB Woodlawn" }
console.log( schools[1] ) // { name: "Stratford" },

const editName = (oldName, name, arr) =>
 arr.map(item => {
 if (item.name === oldName) {
 return {
 ...item,
 name
 }
 } else {
 return item
 }
 })

editName function can be written entirely in one line

const editName = (oldName, name, arr) =>
 arr.map(item => (item.name === oldName) ?
 ({...item,name}) :
 item
 )

Object conversion into array of object

const schools = {
 "Yorktown": 10,
 "Washington & Lee": 2,
 "Wakefield": 5
}
const schoolArray = Object.keys(schools).map(key =>
 ({
 name: key,
 wins: schools[key]
 })
 )
console.log(schoolArray)
// [
// { 
// name: "Yorktown", 
// wins: 10 
// }, 
// { 
// name: "Washington & Lee", 
// wins: 2 
// }, 
// { 
// name: "Wakefield", 
// wins: 5 
// }
// ]

Object.keys returns an array of school names, and we can use map on that array to produce a new array of the same length. The name of the new object will be set using the key, and wins is set equal to the value

Array.reduce()

The reduce and reduceRight functions can be used to transform an array into any value, including a number, string, B Boolean, object, or even a function

Example:

const ages = [21,18,42,40,64,63,34];
const maxAge = ages.reduce((max, age) => {
 console.log(`${age} > ${max} = ${age > max}`);
 if (age > max) {
 return age
 } else {
 return max
 }
}, 0)
console.log('maxAge', maxAge);
// 21 > 0 = true
// 18 > 21 = false
// 42 > 21 = true
// 40 > 42 = false
// 64 > 42 = true
// 63 > 64 = false
// 34 > 64 = false
// maxAge 64

in the above example the ages array has been reduced into a single value: the maximum age, 64. reduce takes two arguments: a callback function and an original value. In this case, the original value is 0, which sets the initial maximum value to 0. The callback is invoked once for every item in the array. The first time this callback is invoked, age is equal to 21, the first value in the array, and max is equal to 0, the initial value. The callback returns the greater of the two numbers, 21, and that becomes the max value during the next iteration. Each iteration compares each age against the max value and returns the greater of the two. Finally, the last number in the array is compared and returned from the previous callback.

Array.reduceRight

Array.reduceRight works the same way as Array.reduce; the difference is that it starts reducing from the end of the array rather than the beginning

An Example to transform an array into an object:

const colors = [
 {
 id: '-xekare',
 title: "rad red",
 rating: 3
 },
 {
 id: '-jbwsof',
 title: "big blue",
 rating: 2
 },
 {
 id: '-prigbj',
 title: "grizzly grey",
 rating: 5
 },
 {
 id: '-ryhbhsl',
 title: "banana",
 rating: 1
 }
]
const hashColors = colors.reduce(
 (hash, {id, title, rating}) => {
 hash[id] = {title, rating}
 return hash
 },
 {}
)
console.log(hashColors);
//output
// {
// "-xekare": {
// title:"rad red",
// rating:3
// },
// "-jbwsof": {
// title:"big blue",
// rating:2
// },
// "-prigbj": {
// title:"grizzly grey",
// rating:5
// },
// "-ryhbhsl": {
// title:"banana",
// rating:1
// }
// }

In the above example , the second argument sent to the reduce function is an empty object. This is our initial value for the hash. During each iteration, the callback function adds a new key to the hash using bracket notation and sets the value for that key to the id field of the array. Array.reduce can be used in this way to reduce an array to a single value of an object.

Distinct array with reduce Example:

const colors = ["red", "red", "green", "blue", "green"];
const distinctColors = colors.reduce(
 (distinct, color) =>
 (distinct.indexOf(color) !== -1) ?
 distinct :
 [...distinct, color],
 []
)
console.log(distinctColors)
// ["red", "green", "blue"]

In this above example, the colors array is reduced to an array of distinct values. The second argument sent to the reduce function is an empty array. This will be the initial value for distinct. When the distinct array does not already contain a specific color, it will be added. Otherwise, it will be skipped, and the current distinct array will be returned

Leave a Comment