Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of years (including BCE)

There is an array of objects containing a chemical element with it's discovery year:

[
   {"name": "hydrogen", "discovered": "1766"},
   {"name": "boron", "discovered": "1808"},
   {"name": "copper", "discovered": "9000 BCE"},
   {"name": "argon", "discovered": "1894"},
   {"name": "iron", "discovered": "before 5000 BCE"},
   {"name": "phosphorus", "discovered": "1669"}
]

What I want is to sort the array in terms of the year discovered, so the oldest (copper in this case) should be the first item and the recent(argon) should be the last item.

//It should look like this in the end:
[
   {"name": "copper", "discovered": "9000 BCE"},
   {"name": "iron", "discovered": "before 5000 BCE"},
   {"name": "phosphorus", "discovered": "1669"},
   {"name": "hydrogen", "discovered": "1766"},
   {"name": "boron", "discovered": "1808"},
   {"name": "argon", "discovered": "1894"}
]

The problem I encountered was the few keywords like "before", "BCE", "CE", that I don't know how to handle.

Is there any solution to handle this problem?

like image 349
Rithish Avatar asked Feb 02 '26 09:02

Rithish


1 Answers

9000 BCE is same as year -9000.

You can simply treat those BCE (keyword before might be ignored, cause it contains BCE anyway) data strings as -year in sort function, as follows:

const data = [{name:"hydrogen",discovered:"1766"},{name:"boron",discovered:"1808"},{name:"copper",discovered:"9000 BCE"},{name:"argon",discovered:"1894"},{name:"iron",discovered:"before 5000 BCE"},{name:"phosphorus",discovered:"1669"}];

const res = data.sort((a, b) => {
  const numA = (a.discovered.includes("BCE") ? -1 : 1)
              * a.discovered.replace(/\D/g, '')
  const numB = (b.discovered.includes("BCE") ? -1 : 1)
              * b.discovered.replace(/\D/g, '')
  return numA - numB
})

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */
like image 115
ulou Avatar answered Feb 03 '26 22:02

ulou