Привет! Метод .sort в массиве с объектами не работает, есть идеи, почему это так? - PullRequest
0 голосов
/ 28 марта 2020
const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, 
{speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32}];

 const sortSpeciesByTeeth = arr => {arr.sort(item=>{
     item.numTeeth;
     })
        return arr
     }
    console.log(sortSpeciesByTeeth(speciesArray))
 The outcome it produces: undefined. 
 The outcome expected : [ { speciesName: 'human', numTeeth: 32 },
  { speciesName: 'dog', numTeeth: 42 },
  { speciesName: 'shark', numTeeth: 50 },
  { speciesName: 'alligator', numTeeth: 80 } ]

Поскольку метод .sort () по умолчанию сортирует числа по порядку отправки, я не использовал никакую функцию сравнения, хотя она не работает так хорошо, но не понимаю, почему. Спасибо за любые предложения

1 Ответ

0 голосов
/ 28 марта 2020

Попробуйте это

const speciesArray = [{ speciesName: 'shark', numTeeth: 50 }, { speciesName: 'dog', numTeeth: 42 },
{ speciesName: 'alligator', numTeeth: 80 }, { speciesName: 'human', numTeeth: 32 }];

function sortSpeciesByTeeth(input) {
    let sortedArray = input.sort((a, b) => (a.numTeeth > b.numTeeth) ? 1 : -1)
    return sortedArray
}

console.log(sortSpeciesByTeeth(speciesArray))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...