Last active
November 15, 2017 05:05
-
-
Save johntran/cd66dba7e8c9d4f136ee373cc031d8c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function map(arr, func) { | |
return arr.map(func); | |
} | |
// IF you are super particular about ordering | |
function parseCSV(csv) { | |
var peopleArray = csv.split('\n'); | |
var peopleArrayWithSplitNameElements = map(peopleArray, function(str){ | |
return str.split(','); | |
}) | |
var result = map(peopleArrayWithSplitNameElements, function(arr){ | |
var personObj = { | |
name: {}, | |
}; | |
if (arr[0]) { | |
personObj.name.first = arr[0]; | |
} | |
if (arr[1]) { | |
personObj.name.middle = arr[1]; | |
} | |
if (arr[2]) { | |
personObj.name.last = arr[2] | |
} | |
if (arr[3]) { | |
personObj.age = arr[3]; | |
} | |
return personObj; | |
}) | |
return result; | |
} | |
// How people would actually write it | |
function parseCSV(csv) { | |
var peopleArray = csv.split('\n'); | |
var peopleArrayWithSplitNameElements = map(peopleArray, function(str){ | |
return str.split(','); | |
}) | |
var result = map(peopleArrayWithSplitNameElements, function(arr){ | |
var personObj = { | |
name: { | |
first: arr[0], | |
last: arr[2], | |
}, | |
age: arr[3], | |
}; | |
if (arr[1]) { | |
personObj.name.middle = arr[1]; | |
} | |
return personObj; | |
}) | |
return result; | |
} | |
// using native functions | |
// function parseCSV(csv) { | |
// return csv.split('\n') | |
// .map(function(str) { | |
// return str.split(',') | |
// }) | |
// .map(function(arr) { | |
// var personObj = { | |
// name: { | |
// first: arr[0], | |
// last: arr[2], | |
// }, | |
// age: arr[3], | |
// }; | |
// if (arr[1]) { | |
// personObj.name.middle = arr[1]; | |
// } | |
// return personObj; | |
// }) | |
// } | |
var csv = "Alyssa,P.,Hacker,26\nBen,,Bitdiddle,34\nEva,Lu,Ator,40\nLem,E.,Tweakit,45\nLouis,,Reasoner,21" | |
console.log(parseCSV(csv)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment