javascript - Sorting an array of objects by multiple criteria with null values -


alright, have array of objects includes null values property.

the object looks sorting purposes... (40 elements, suffice...).

it needs sorted based on roulette descending (with roulette being null), novelty, popularity.

my head getting bit crushed.

this works sort roulette in descending, how need extend include other 2 criteria?

object:

[  {   title: 'one',   popularity: 4,   novelty: 3  },  {   title: 'two',   popularity: 1   novelty: 4  },  {   title: 'three',   popularity: 5,   novelty: 3,   roulette: 0  },  {   title: 'four',   popularity: 5,   novelty: 3,   roulette: 1  } ] 

partially working function:

  object.sort(function(a, b) {     if (a['roulette'] == null) return 1     if (b['roulette'] == null) return -1     if (a['roulette'] === b['roulette']) return 0     return b.roulette > a.roulette ? 1 : -1   }); 

an attempt sorting priority , groups.

var data = [{ title: 'one', popularity: 4, novelty: 3 }, { title: 'two', popularity: 1, novelty: 4 }, { title: 'three', popularity: 5, novelty: 3, roulette: 0 }, { title: 'four', popularity: 5, novelty: 3, roulette: 1 }, { title: 'five', popularity: 5, novelty: 4, roulette: null }, { title: 'six', popularity: 5, novelty: 5, roulette: undefined }];    data.sort(function (a, b) {      return (          (a.roulette === undefined || a.roulette === null) - (b.roulette === undefined || b.roulette === null) ||          a.roulette - b.roulette ||          a.novelty - b.novelty ||          a.popularity - b.popularity      );         });    console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -