Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sorting using Typescript/ javascript

I have the following data:

Data = [
  { "rock": "granite", "youngerThan": "schist"},
  { "rock": "basalt", "youngerThan": null},
  { "rock": "Picrite", "youngerThan": "granite"},
  { "rock": "schist", "youngerThan": "basalt"}
]

etc and I would like to get a sorted array for rock based on attribute youngerThan. Note that youngerThan can be undefined which means this rock is the oldest (at the bottom).

Thus what I want to obtain is the following list: (oldest to youngest)

basalt, schist, granite, picrite

youngest to oldest

picrite,granite, schist, basalt

like image 838
user8978916 Avatar asked May 15 '26 05:05

user8978916


1 Answers

    // Case sensitivity
    var data = [ { "rock": "granite", "youngerThan": "schist"},{ "rock": "schist", "youngerThan": "basalt"},{ "rock": "basalt" },{ "rock": "granite", "youngerThan": "Picrite"}]

    data.sort((a,b) =>{
        if(!a.youngerThan || a.youngerThan < b.youngerThan){
         return -1
        }else if (!b.youngerThan || a.youngerThan > b.youngerThan){
          return 1
        }
        return 0
    })

    console.log(data);

// Case insensitivity
var data = [ { "rock": "granite", "youngerThan": "schist"},{ "rock": "schist", "youngerThan": "basalt"},{ "rock": "basalt" },{ "rock": "granite", "youngerThan": "Picrite"}]

data.sort((a,b) =>{
    var nameA = a.youngerThan ? a.youngerThan.toUpperCase() : null ; // ignore upper and lowercase
    var nameB = b.youngerThan ? b.youngerThan.toUpperCase() : null ; // ignore upper and lowercase
    if(!nameA || nameA < nameB){
     return -1;
    }else if (!nameB || nameA > nameB){
      return 1;
    }
    return 0;
})

console.log(data);
like image 163
edkeveked Avatar answered May 17 '26 19:05

edkeveked



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!