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

63
Views
Ordenar una matriz por su valor de objeto

Quiero ordenar esta matriz por su objeto xp:

 [ ["438449925949489153", { "xp": 2 }], ["534152271443415140", { "xp": 3 }], ["955210908794236938", { "xp": 1 }] ]

Para que devuelva esta matriz:

 [ ["955210908794236938", { "xp": 1 }], ["438449925949489153", { "xp": 2 }], ["534152271443415140", { "xp": 3 }] ]

Intenté hacer esto con el módulo sort-json npm pero ordenó el primer valor en lugar de xp

 const sortJson = require('sort-json'); sortJson(array)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puedes usar el tipo nativo:

 let data = [ ["438449925949489153", { "xp": 2 }], ["955210908794236938", { "xp": 3 }], ["955210908794236938", { "xp": 1 }] ]; const ascending = (a,b) => a[1].xp - b[1].xp; const descending = (a,b) => b[1].xp - a[1].xp; data.sort(ascending); console.log(data) data.sort(descending); console.log(data)

Tenga en cuenta que sort muta la matriz original: si no desea hacer eso, debe realizar una copia superficial de la matriz original.

about 4 years ago · Juan Pablo Isaza Report

0

orden descendiente:

 arr.sort((a,b) =>{ if (a[1].xp < b[1].xp) return 1 else return -1 })

orden ascendente:

 arr.sort((a,b) =>{ if (a[1].xp < b[1].xp) return -1 else return 1 })
about 4 years ago · Juan Pablo Isaza Report

0

Sugeriría una implementación un poco más limpia:

 function compare( a, b ) { if ( a[1] < b[1]){ return -1; } if ( a[1] > b[1] ){ return 1; } return 0; } arr.sort( compare );

O de una sola línea:

 arr.sort((a,b) => (a[1] > b[1]) ? 1 : ((b[1] > a[1]) ? -1 : 0))
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!