[Sort array of object by property value]
I want to compare the amount of upvotes and sort, but I have a problem with understanding how to get to the object "ups" from my api. I created the compare function and I want to call it. I probably call it on the wrong object.
function fetchData(url) {
return fetch(url).then((resp) => resp.json());
}
function createTableRow(data) {
const tableRow = document.createElement('tr');
const {
title,
ups,
downs,
score,
num_comments,
created
} = data;
console.log(ups);
tableRow.appendChild(createElement('td', title))
tableRow.appendChild(createElement('td', ups))
tableRow.appendChild(createElement('td', downs))
tableRow.appendChild(createElement('td', score))
tableRow.appendChild(createElement('td', num_comments))
tableRow.appendChild(createElement('td', created))
return tableRow;
}
function createElement(tag_name, text) {
const el = document.createElement(tag_name);
const content = document.createTextNode(text);
el.appendChild(content);
return el;
}
**function compare(a,b) {
if(a.ups<b.ups) {
return -1;
}
if(a.ups>b.ups){
return 1;
}
return 0;
}**
const butt = document.getElementById('button');
const swTable = document.getElementById('sw_table').getElementsByTagName('tbody')[0];
fetchData('https://www.reddit.com/r/funny.json')
.then(data => {
data.data.children.forEach(result => {
const table = createTableRow(result.data);
swTable.appendChild(table);
// butt.onclick(sortData(ups));
**data.data.children.ups.sort(compare);**
});
});
Error: Uncaught (in promise) TypeError: Cannot read property 'sort' of undefined