Created
October 16, 2018 18:48
-
-
Save cferdinandi/c39cf84a287f2c041882a1495ebc978f to your computer and use it in GitHub Desktop.
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>ConsolidateJS</title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var data = [ | |
{ | |
"name": "Jeff", | |
"type": "olympic", | |
"quantity": "5" | |
}, | |
{ | |
"name": "Jeff", | |
"type": "half_iron", | |
"quantity": "2" | |
}, | |
{ | |
"name": "Sally", | |
"type": "olympic", | |
"quantity": "7" | |
}, | |
{ | |
"name": "Sally", | |
"type": "half_iron", | |
"quantity": "4" | |
}, | |
]; | |
/** | |
* Consolidate data into a new array | |
* @param {Array} data The original data | |
* @return {Array} The consolidated data | |
*/ | |
var consolidate = function (data) { | |
// If no data is provided, throw an error | |
if (!data) throw new Error('Please provide data'); | |
// Create a new array | |
var newArr = []; | |
// Loop through the existing data | |
data.forEach(function (item) { | |
// Check if an array entry with the item.name already exists | |
var exists = newArr.find(function (existing) { | |
return existing.name === item.name; | |
}); | |
// If so, add the item.type: item.quantity to it | |
// Otherwise, create a new object and push it to the new array | |
if (exists) { | |
exists[item.type] = item.quantity; | |
} else { | |
var newObj = {}; | |
newObj.name = item.name; | |
newObj[item.type] = item.quantity; | |
newArr.push(newObj); | |
} | |
}); | |
// Return the new array | |
return newArr; | |
}; | |
var data2 = consolidate(data); | |
console.log(data2); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment