0

[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

Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
  • What does your data look like? – VLAZ May 20 '19 at 11:19
  • @U25lYWt5IEJhc3RhcmQg I iniatally thought I'd need to link that yet again, but it appears to be different. OP isn't asking how to do it but why it doesn't work after it's done. – VLAZ May 20 '19 at 11:29
  • @VLAZ : I don't really think it is any different, the very first [answer](https://stackoverflow.com/a/56219966/11299053) seems to deliver what's needed – Yevhen Horbunkov May 20 '19 at 11:34
  • @U25lYWt5IEJhc3RhcmQg this question is about an error when OP already has sorting by property. It's not about "how to sort by property". It's very likely OP has already seen the other question and tried to implement it but has now ran into an issue that it's not sorting. Pointing them back at "how to do it" wouldn't necessarily help. – VLAZ May 20 '19 at 11:36
  • 3
    Possible duplicate of [Sorting an array of JavaScript objects by property](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects-by-property) – Armen Michaeli May 20 '19 at 11:53

3 Answers3

1

Here is what you should use:

fetchData('https://www.reddit.com/r/funny.json')
  .then(data => {
    const sortedResults = data.data.children.sort((a,b) => b.data.ups - a.data.ups)
    sortedResults.forEach(result => {
      const row = createTableRow(result.data);
      swTable.appendChild(row);
    })
  });
});
  • You must sort directly on the results
  • a.data.ups - b.data.ups will return either a negative number if a has more ups than b, a positive number if b has more ups than a, and 0 if they have the same amount of ups
Errorname
  • 2,228
  • 13
  • 23
0

If considered that API return data in format:

{
   "data": {
       children: [
          {
             title,
             ups,
             downs,
             score,
             num_comments,
             created
          }
       ]

   }
}

Modifying then function as below will solve your problem.

 .then(data => {
    data.data.children.sort(compare)
      .forEach(result => {
         const table = createTableRow(result);
         swTable.appendChild(table);
      })
});
0

Change the below line,

**data.data.children.ups.sort(compare);**

to,

data.data.children.sort((a,b)=>a.ups-b.ups); // ascending

data.data.children.sort((a,b)=>b.ups-a.ups); // descending
Manish Khedekar
  • 392
  • 3
  • 13