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

151
Views
Ordenar una matriz usando .sort en una función es igual a Undefined en JavaScript

Quiero crear una nueva matriz que sea una copia de la mía y al mismo tiempo ordenarla usando el valor almacenado en numTeeth. Estoy usando la función ordenar para realizar esta tarea. El problema es que si trato de depurarlo usando un registro de consola, muestra como resultado el valor indefinido.

 const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32} ]; const sortSpeciesByTeeth = arrayIn => { arrayIn.sort( function (a, b) { return a.numTeeth - b.numTeeth; }); } console.log(sortSpeciesByTeeth(speciesArray))

Mientras que si uso el mismo código sin declararlo como una función separada, funciona a pesar de ordenar la matriz original. Lo que no quiero en el código final. Ejemplo

 const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32} ]; speciesArray.sort( function (a, b) { return a.numTeeth - b.numTeeth; }); console.log(speciesArray)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

1) Tienes que return algo de la función sortSpeciesByTeeth , por defecto se devuelve undefind .

2) Si desea una copia de la matriz original, puede usar la sintaxis extendida

El método sort() ordena los elementos de una matriz en su lugar y devuelve la matriz ordenada. - MDN

 const sortSpeciesByTeeth = (arrayIn) => { return [...arrayIn.sort((a, b) => a.numTeeth - b.numTeeth)]; };

o

 const sortSpeciesByTeeth = (arrayIn) => [ ...arrayIn.sort(({ numTeeth: nT1 }, { numTeeth: nT2 }) => nT1 - nT2), ]; 

 const speciesArray = [ { speciesName: "shark", numTeeth: 50 }, { speciesName: "dog", numTeeth: 42 }, { speciesName: "alligator", numTeeth: 80 }, { speciesName: "human", numTeeth: 32 }, ]; const sortSpeciesByTeeth = (arrayIn) => { return [ ...arrayIn.sort(function (a, b) { return a.numTeeth - b.numTeeth; }), ]; }; console.log(sortSpeciesByTeeth(speciesArray));
 /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

En una función de flecha JS, la primera declaración solo se devuelve implícitamente si el cuerpo de su función no está entre llaves. Esto significa que sortSpeciesByTeeth no devuelve nada. Solo necesita agregar una declaración de return :

 const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32} ]; const sortSpeciesByTeeth = arrayIn => { return arrayIn.sort(function (a, b) { return a.numTeeth - b.numTeeth; }); } console.log(sortSpeciesByTeeth(speciesArray))

Su función sortSpeciesByTeeth original en realidad estaba ordenando la lista, pero simplemente se caía al final sin devolver nada, por lo tanto, devolvía implícitamente undefined a la instrucción console.log . (Entonces, si ordenó la matriz antes de iniciar sesión, también habría obtenido el resultado deseado):

 const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32} ]; const sortSpeciesByTeeth = arrayIn => { arrayIn.sort(function (a, b) { return a.numTeeth - b.numTeeth; }); } sortSpeciesByTeeth(speciesArray) console.log(speciesArray)

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!