Last active
December 31, 2019 23:20
-
-
Save mrbusche/34291324cc4f73f01090a07aa9e509d0 to your computer and use it in GitHub Desktop.
combine json with same key
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
</head> | |
<body> | |
<div id="combined"></div> | |
<script> | |
const request = new XMLHttpRequest(); | |
request.open('GET', 'combined.json'); | |
request.responseType = 'json'; | |
let players; | |
let combinedData = []; | |
request.onload = function() { | |
players = request.response; | |
for (let player in players) { | |
let playerName = players[player].name; | |
playerName = playerName.replace(' Jr.', ' Jr'); | |
playerName = playerName.replace(' Jr', ''); | |
playerName = playerName.replace(' IV', ''); | |
playerName = playerName.replace(' III', ''); | |
playerName = playerName.replace(' II', ''); | |
playerName = playerName.replace('DJ ', 'D.J. '); | |
playerName = playerName.replace('DK ', 'D.K. '); | |
playerName = playerName.replace('JJ ', 'J.J. '); | |
if (playerName === 'Will Fuller V') { | |
playerName = 'Will Fuller'; | |
} else if (playerName === 'Olabisi Johnson') { | |
playerName = 'Bisi Johnson'; | |
} else if (playerName === 'C.J Anderson') { | |
playerName = 'C.J. Anderson'; | |
} else if (playerName === 'LeVeon Bell') { | |
playerName = "Le'Veon Bell"; | |
} else if (playerName === 'Mitch Trubisky') { | |
playerName = 'Mitchell Trubisky'; | |
} else if (playerName === '') { | |
playerName = ''; | |
} | |
const found = combinedData.find(element => element.name === playerName); | |
if (found === undefined) { | |
let newPlayer = { name: playerName, val: players[player].value, count: 1 }; | |
combinedData.push(newPlayer); | |
} else { | |
let ind = combinedData.findIndex(elem => elem.name === playerName); | |
let combinedValue = players[player].value + found.val; | |
let combinedCount = found.count + 1; | |
combinedData[ind].val = combinedValue; | |
combinedData[ind].count = combinedCount; | |
} | |
} | |
let theData = []; | |
for (let data in combinedData) { | |
theData.push({ name: combinedData[data].name, value: combinedData[data].val / combinedData[data].count }); | |
} | |
theData.sort((a, b) => (a.value > b.value ? 1 : -1)); | |
theData.sort((a, b) => (a.name > b.name ? 1 : -1)); | |
const display = document.getElementById('combined'); | |
for (let d in theData) { | |
display.innerHTML += theData[d].name + ' ' + theData[d].value + '<br>'; | |
} | |
}; | |
request.send(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment