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)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; }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)