JavaScript Data Wrangling Cheat Sheet

2y ago
11 Views
2 Downloads
471.21 KB
13 Pages
Last View : 22d ago
Last Download : 2m ago
Upload by : Cade Thielen
Transcription

Run this notebook with Data-Forge NotebookJavaScript data wrangling cheat sheetSnippets of JS code that are good for working with data.From the book Data Wrangling with JavaScriptLOGGINGLogging is your best friend. Use console.log to display, inspect and check your data.console.log("Your logging here"); // General text logging for debugging.Your logging hereconst arr [1, 2, 3];console.log(arr);// Your data.[ 1, 2, 3 ]const obj { A: 1, B: 2, C: 3 }; // Your dataconsole.log(obj);{ A: 1, B: 2, C: 3 }In Data-Forge Notebook you can also use the display function for formatted output:const obj { A: 1, B: 2, C: 3 }; // Your datadisplay(obj);"root" : { 3 items"A" : 1"B" : 2"C" : 3}OBJECTSTechniques for creating and modifying JavaScript objects.Extract a fieldlet o { A: 1, B: 2 };let v1 o["A"];display(v1);// Your data// Extract field value

let v2 o.A;display(v2);11Set a fieldlet o {};o["A"] 3;o.A 3;// Empty object// Set field valuedisplay(o);"root" : { 1 item"A" : 3}Delete a fieldlet o { A: 1, B: 2 };delete o["A"];delete o.A;// Delete a field valuedisplay(o);"root" : { 1 item"B" : 2}Clone an objectletletc.Ac.Boc { A: 1, B: 2 }; Object.assign({}, o);300;500;display(o);display(c);"root" : { 2 items"A" : 1"B" : 2}"root" : { 2 items"A" : 300"B" : 500}Replace fields in an object// Clone an object// Original object is unchanged// Cloned object is modified

Replace fields in an objectlet o { A: 1, B: 2 };let ovr { B: 200 };let c Object.assign({}, o, ovr);// Clone and override fieldsdisplay(o);display(c);// Original object is unchanged// Cloned object has specified fields"root" : { 2 items"A" : 1"B" : 2}"root" : { 2 items"A" : 1"B" : 200}ARRAYSTechniques for creating and modifying JavaScript arrays.Visit each itemlet a [1, 2, 3];a.forEach(item {console.log(item);});// Your data// Visit each item in the array// Or (old-style JS)for (let i 0; i a.length; i) {const item a[i];// Visit each item}// Or (using modern JS iterators)for (const item of a) {// Visit each item}123Getting and setting valueslet a [1, 2, 3, 4, 5, 6];let v a[5];display(v);// Your data// Get value at index

a[3] 32;display(a);// Set value at index6"root" : [ 6 items0 : 11 : 22 : 33 : 324 : 55 : 6]Adding and removing itemslet a [1, 2, 3];a.push("new end item");display(a);// Add to end of arraylet last a.pop();display(last);display(a);// Remove last elementa.unshift("new start item");display(a);// Add to start of arraylet first a.shift();display(first);display(a);// Remove first element"root" : [ 4 items0 : 11 : 22 : 33 : "new end item"]new end item"root" : [ 3 items0 : 11 : 22 : 3]"root" : [ 4 items0 : "new start item"1 : 12 : 23 : 3]new start item"root" : [ 3 items0 : 11 : 22 : 3

]Concatenate arrayslet a1 [1, 2, 3];let a2 [4, 5, 6];let a a1.concat(a2);display(a);// Concatenate arrays"root" : [ 6 items0 : 11 : 22 : 33 : 44 : 55 : 6]Extracting portions of an arraylet a [1, 2, 3, 4, 5];let e a.slice(0, 3);display(e);// Extract first 3 elements"root" : [ 3 items0 : 11 : 22 : 3]let a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];let e a.slice(5, 11);display(e);// Extract elements 5 to 10"root" : [ 6 items0 : 61 : 72 : 83 : 94 : 105 : 11]let a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];let e a.slice(-4, -1);display(e);"root" : [ 3 items0 : 7// Negative indicies relative to end

1 : 82 : 9]let a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];let e a.slice(-3);display(e);// Extract last three elements"root" : [ 3 items0 : 81 : 92 : 10]Clone an arraylet a [1, 2, 3, 4, 5];let c a.slice();c[2] 2230;display(a);display(c);// Clone array// Original array is unchanged// Cloned array is modified"root" : [ 5 items0 : 11 : 22 : 33 : 44 : 5]"root" : [ 5 items0 : 11 : 22 : 22303 : 44 : 5]Find an element in an arraylet a [1, 2, 3, 4, 5];let i a.indexOf(3);if (i 0) {let v a[i];display(v);}3Sorting an array// Find index of item in array// The value exists, extract it

let a ["Pineapple", "Orange", "Apple", "Bananna"];a.sort();display(a);"root" : [ 4 items0 : "Apple"1 : "Bananna"2 : "Orange"3 : "Pineapple"]let a ["Pineapple", "Orange", "Apple", "Bananna"];let c a.slice();// Clone the originalc.sort();// Sort array without modifying the odisplay(a);// Original array is unmodifieddisplay(c);// Cloned array is sorted"root" : [ 4 items0 : "Pineapple"1 : "Orange"2 : "Apple"3 : "Bananna"]"root" : [ 4 items0 : "Apple"1 : "Bananna"2 : "Orange"3 : "Pineapple"]let a [10, 20, 8, 15, 12, 33];a.sort((a, b) b - a);display(a);// Customize sort with a user-defined"root" : [ 6 items0 : 331 : 202 : 153 : 124 : 105 : 8]FUNCTIONAL JAVASCRIPTFunctional-style array manipulation techniques.FilterFilter an array with filter and a user-defined predicate function.

let a [10, 20, 8, 15, 12, 33];function predicate(value) {return value 10;}let f a.filter(v predicate(v));display(f);// Retain values 10// Filter array"root" : [ 4 items0 : 201 : 152 : 123 : 33]TransformTransform an array with map and a user-defined transformation function.let a [1, 2, 3, 4, 5];function transform(value) {return value 1;}let t a.map(v transform(v));display(t);// Increment all values by one.// Transform array"root" : [ 5 items0 : 21 : 32 : 43 : 54 : 6]AggregationAggregate an array with reduce and a user-defined aggregation function.let a [1, 2, 3, 4, 5];function sum(a, b) {return a b;}let t a.reduce(sum, 0)display(t);// Produces the sum of all values.// Reduce the array by summing the total of all va15REGULAR EXPRESSIONS

REGULAR EXPRESSIONSUse regular expressions to match and extract search patterns in text.let re /search pattern/;// Define regular expression// Orre new RegExp("search pattern");// Or add optionsre /search pattern/ig// Case insensitive globallet source "your text data that contains the search pattern";let match re.exec(source);// Find first match.display(match);while ((match re.exec(source)) ! null) {// Find each match in turn.}"root" : [ 1 item0 : "search pattern"]READ AND WRITE TEXT FILESIn Node.js we can read and write text files using the fs module functionsfs.readFileSync and fs.writeFileSync.After you run this code cell, check out the contents of the file my-text-file.txt that hasbeen written out to your file system.const fs require('fs');const textData "My text data";fs.writeFileSync("./my-text-file.txt", textData);const loadedTextData fs.readFileSync("./my-text-file.txt", "utf8");display(loadedTextData);My text dataDATA FORMATSSerialize and deserialize JSON dataJavaScript already contains the functions you need to to serialize and deserialize data toand from the JSON format.Use JSON.stringify to convert your data to JSON, then use JSON.parse to convert itback.

const{{{];constdata [item: "1" },item: "2" },item: "3" }jsonData JSON.stringify(data);// Serialize (encode) the arrdisplay(jsonData);const deserialized JSON.parse(jsonData);display(deserialized);// Deserialize (decode) the a[{"item":"1"},{"item":"2"},{"item":"3"}]"root" : [ 3 items0 : { 1 item"item" : "1"}1 : { 1 item"item" : "2"}2 : { 1 item"item" : "3"}]Read and write JSON data filesIf we combine the fs functions with the JSON functions we can now read and write JSONdata files.After you run this code cell, check out the contents of the file my-json-file.json thathas been written out to your file system.const fs require('fs');const data [{ item: "1" },{ item: "2" },{ item: "3" }];fs.writeFileSync("./my-json-file.json", JSON.stringify(data));const deserialized JSON.parse(fs.readFileSync("./my-json-file.json", "utf8"display(deserialized);"root" : [ 3 items0 : { 1 item"item" : "1"}1 : { 1 item"item" : "2"}2 : { 1 item

"item" : "3"}]Serialize and deserialize CSV dataLet's not forget about working with CSV data, it's a staple of the data science community!Unfortunately JavaScript doesn't provide us with functions to do this, so we'll turn to theexcellent PapaParse library available via npm.Note the use of the dynamicTyping option - this is quite important as it causes PapaParseto deserialized CSV columns that contain numbers and booleans (unfortunately it doesn'thelp with dates).const Papa require('papaparse');const{{{];constdata [item: "1", val: 100 },item: "2", val: 200 },item: "3", val: 300 }csvData Papa.unparse(data);// Serialize (encode)display(csvData);const options { dynamicTyping: true, header: true };const deserialized Papa.parse(csvData, options);display(deserialized.data);// Deserialize (decoditem,val 1,100 2,200 3,300"root" : [ 3 items0 : { 2 items"item" : 1"val" : 100}1 : { 2 items"item" : 2"val" : 200}2 : { 2 items"item" : 3"val" : 300}]Read and write CSV data filesWe can also combine the fs functions with PapaParse and be able to read and write CSVdata files.After you run this code cell, check out the contents of the file my-csv-file.csv that hasbeen written out to your file system.

const fs require('fs');const Papa require('papaparse');const data [{ item: "1", val: 100 },{ item: "2", val: 200 },{ item: "3", val: 300 }];fs.writeFileSync("./my-csv-file.csv", Papa.unparse(data));const options { dynamicTyping: true, header: true };const deserialized Papa.parse(fs.readFileSync("./my-csv-file.csv", "utf8"display(deserialized.data);"root" : [ 3 items0 : { 2 items"item" : 1"val" : 100}1 : { 2 items"item" : 2"val" : 200}2 : { 2 items"item" : 3"val" : 300}]Getting data from a REST APIUse the axios module to retreive data from a REST API (with data from JSONPlaceholder).const axios require('axios');const response await const data response.data;display(data.slice(0, 5));"root" : [ 5 items0 : { 4 items"userId" : 1"id" : 1"title" : "delectus aut autem""completed" : false}1 : { 4 items"userId" : 1"id" : 2"title" : "quis ut nam facilis et officia qui""completed" : false}2 : { 4 items

"userId" : 1"id" : 3"title" : "fugiat veniam minus""completed" : false}3 : { 4 items"userId" : 1"id" : 4"title" : "et porro tempora""completed" : true}4 : { 4 items"userId" : 1"id" : 5"title" : "laboriosam mollitia et enim quasi adipisci quia provident illum""completed" : false}]This notebook exported from Data-Forge Notebook

JavaScript data wrangling cheat sheet Snippets of JS code that are good for working with data. From the book Data Wrangling with JavaScript LOGGING Logging is your best friend. Use console.log to display, inspect an

Related Documents:

Cissp cheat sheet all domains. Cissp cheat sheet 2022 pdf. Cissp cheat sheet 2022. Cissp cheat sheet domain 4. Cissp cheat sheet pdf. Cissp cheat sheet 2021. Cissp cheat sheet domain 1. Cissp cheat sheet reddit. We use cookies to offer you a better browsing experience, analyze site traffic, personalize content, and serve targeted advertisements.

Data wrangling This chapter introduces basics of how to wrangle data in R. Wrangling skills will provide an intellectual and practical foundation for working with modern data. 4.1 A grammar for data wrangling In much the same way that ggplot2 presents a grammar for data graphics, the dplyr package presents a grammar for data wrangling [234].

Git-cheat-sheet Optional Reading: Bourbon-cheat-sheet CLI-cheat-sheet Git-for-subversion-cheat-sheet Tower-cheat-sheet (for Mac or Windows depending on your computer) Website_optimization-cheat-sheet Workflow-of-version-control Xcode-cheat-sheet _tower-git-client (

Google Slides Cheat Sheet p. 15-18 Google Sheets Cheat Sheet p. 19-22 Google Drawings Cheat Sheet p. 23-26 Google Drive for iOS Cheat Sheet p. 27-29 Google Chrome Cheat Sheet p. 30-32 ShakeUpLearning.com Google Cheat Sheets - By Kasey Bell 3

The Excel 2010 Ribbon looks and works much the same as the Excel 2007 Ribbon, with one nifty addition: In Excel 2010, you can customize what's on the Ribbon. In this series Word 2010 cheat sheet Excel 2010 cheat sheet Outlook 2010 cheat sheet PowerPoint 2010 cheat sheet The Scrollbar.

JavaScript Manual for LCCS Teachers 13 Client-side JavaScript vs. server-side JavaScript For many years JavaScript was a client-side scripting language. This was because JavaScript programs could only be run from inside web browsers which were installed on client machines. Because of the fact that JavaScript code can run on client devices it means

- The Spark web app framework . Yahoo JavaScript PHP Amazon.com JavaScript Java, C , Perl Wikipedia.org JavaScript PHP, Hack Twitter.com JavaScript C , Java, Scala, Ruby Bing JavaScript ASP.net eBay.com JavaScript Java, JavaScript, Scala . Note the MVC architecture

3006 AGMA Toilet Additive 1338 (3006) 19.0% 2914 CERAVON BLUE V10 DC (2914) 0.05% 2922 FORMALDEHYDE REODORANT ALTERNATIVE (2922) 0.6% 3 Water (3) 80.05% Constituent Chemicals 1 Water (3) 80.05% CAS number: 7732-18-5 EC number: 231-791-2 Product number: — EU index number: — Physical hazards Not Classified Health hazards Not Classified Environmental hazards Not Classified 2 Bronopol (INN .