Skip to content
codingtube

codingtube

Coding and Programming tutorials

  • javascript
  • React
  • ES6
  • React js
  • coding
  • ffmpeg
  • java
  • programming
  • information
  • coding
  • Privacy Policy
  • Twitter trends
  • Age Calculatore
  • Codingtube Community
  • YouTube Tags Generator
  • About
  • Toggle search form

How Data Transformations works in Javascript ?

Posted on June 9, 2021December 2, 2021 By christo No Comments on How Data Transformations works in Javascript ?

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

javascript, programming Tags:Data Transformations, javascript

Post navigation

Previous Post: What is Pure function in javascript ES6 ?
Next Post: What is Higher-Order Functions in functional programming of javascript ?

Related Posts

Abstract class in Java coding
What is The Spread Operator in javascript ES6 ? javascript
What is Destructuring Assignment in javascript ES6 ? javascript
What is Immutability in javascript Functional Concepts ? javascript
What is Module in javascript ES6 ? coding
Servlets in Java java

Leave a Reply Cancel reply

You must be logged in to post a comment.

Recent Posts

  • Affiliate Marketing Principles
  • The Basics You Need to Know About Affiliate Marketing
  • Affiliate Marketing Options
  • All About Affiliate Marketing
  • Classification of Database Management Systems
  • Three-Tier and n-Tier Architectures
    for Web Applications
  • Two-Tier Client/Server Architectures for DBMSs
  • Basic Client/Server Architectures in DBMS
  • Centralized DBMSs Architecture in DBMS
  • Tools, Application Environments, and Communications Facilities in DBMS

Categories

  • Affiliate marketing (5)
  • Algorithm (43)
  • amp (3)
  • android (223)
  • Android App (8)
  • Android app review (4)
  • android tutorial (60)
  • Artificial intelligence (61)
  • AWS (3)
  • bitcoin (8)
  • blockchain (1)
  • c (5)
  • c language (105)
  • cloud computing (4)
  • coding (4)
  • coding app (4)
  • complex number (1)
  • Computer Graphics (66)
  • data compression (65)
  • data structure (188)
  • DBMS (44)
  • digital marketing (9)
  • distributed systems (11)
  • ffmpeg (26)
  • game (3)
  • html (6)
  • image processing (35)
  • Inequalities (1)
  • information (4)
  • java (212)
  • java network (1)
  • javascript (9)
  • kotlin (4)
  • leetcode (1)
  • math (21)
  • maven (1)
  • mysql (1)
  • Node.js (8)
  • operating system (109)
  • php (310)
  • Principle Of Mathematical Induction (1)
  • programming (6)
  • Python (4)
  • Python data structure (9)
  • React native (1)
  • React.js (22)
  • Redux (1)
  • seo (4)
  • set (12)
  • trigonometry (6)
  • vue.js (35)
  • XML (3)

sitemap

sitemap of videos

sitemap of webstories

sitemap of website

  • Affiliate marketing
  • Algorithm
  • amp
  • android
  • Android App
  • Android app review
  • android tutorial
  • Artificial intelligence
  • AWS
  • bitcoin
  • blockchain
  • c
  • c language
  • cloud computing
  • coding
  • coding app
  • complex number
  • Computer Graphics
  • data compression
  • data structure
  • DBMS
  • digital marketing
  • distributed systems
  • ffmpeg
  • game
  • html
  • image processing
  • Inequalities
  • information
  • java
  • java network
  • javascript
  • kotlin
  • leetcode
  • math
  • maven
  • mysql
  • Node.js
  • operating system
  • php
  • Principle Of Mathematical Induction
  • programming
  • Python
  • Python data structure
  • React native
  • React.js
  • Redux
  • seo
  • set
  • trigonometry
  • vue.js
  • XML
  • Blog
  • Data compression tutorial - codingpoint
  • How to change mbstring in php 5.6
  • How to diagnose out of memory killed PHP-FPM
  • Introduction to jQuery
  • Privacy
  • Affiliate marketing
  • Algorithm
  • amp
  • android
  • Android App
  • Android app review
  • android tutorial
  • Artificial intelligence
  • AWS
  • bitcoin
  • blockchain
  • c
  • c language
  • cloud computing
  • coding
  • coding app
  • complex number
  • Computer Graphics
  • data compression
  • data structure
  • DBMS
  • digital marketing
  • distributed systems
  • ffmpeg
  • game
  • html
  • image processing
  • Inequalities
  • information
  • java
  • java network
  • javascript
  • kotlin
  • leetcode
  • math
  • maven
  • mysql
  • Node.js
  • operating system
  • php
  • Principle Of Mathematical Induction
  • programming
  • Python
  • Python data structure
  • React native
  • React.js
  • Redux
  • seo
  • set
  • trigonometry
  • vue.js
  • XML
  • Blog
  • Data compression tutorial - codingpoint
  • How to change mbstring in php 5.6
  • How to diagnose out of memory killed PHP-FPM
  • Introduction to jQuery
  • Privacy

© codingtube.tech