Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
sort array with 2 conditions, one numeric and the other based on another array

I have been looking for a way to sort an array based on 2 conditions:

First: Sort it based on another array, one being like this: This is the json file to read:

let versiones = ['versionZ', 'versionJ', 'versionA', 'versionK', 'versionC']

If it is not present in the versions array, put them last

Second: Then order it based on its priority present within the elements.

Note: The priority will always exist, it may be that in some cases the key: version does not exist or is shown as null.

Here it would be the array that I want to order without complete success:

    [
        { "name": "Juan", "priority": 10, "version": "versionM" },
        { "name": "Manuel", "priority": 5, "version": "versionA" },
        { "name": "Carlos", "priority": 20, "version": "versionJ" },
        { "name": "Raul", "priority": 12, "version": "versionC" }     
    ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

let LevelOnePriority = ["Z", "J", "A", "K", "C"];

let obj = [
    { name: "Juan", levelTwoPriority: 10, version: "M", },
    { name: "Manuel", levelTwoPriority: 5, version: "L", },
    { name: "Carlos", levelTwoPriority: 20, version: "Z", },
    { name: "Raul", levelTwoPriority: 12, version: "C", },
    { name: "Park22", levelTwoPriority: 7, version: "A", },
    { name: "City25", levelTwoPriority: 6, version: "A", },
];

obj.sort(function(a, b) {
  // "a" is in the highestPriorityArray and "b" isn't
  if (LevelOnePriority.includes(a.version) && !LevelOnePriority.includes(b.version)) {
    return -1;
  }
  // "b" is in the highestPriorityArray and "a" isn't
  if (!LevelOnePriority.includes(a.version) && LevelOnePriority.includes(b.version)) {
    return +1;
  }

  // Both "a" and "b" are in the highestPriorityArray
  if (LevelOnePriority.includes(a.version) && LevelOnePriority.includes(b.version)) {
    // "a" and "b" aren't in the same version
    if (LevelOnePriority.indexOf(a.version) !== LevelOnePriority.indexOf(b.version)) {
      // 
      return LevelOnePriority.indexOf(a.version) - LevelOnePriority.indexOf(b.version);
    }
  }

  return a.levelTwoPriority - b.levelTwoPriority;
});

console.log(obj);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!