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
// 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With