Skip to content

Files

Latest commit

author
juanantonioledesma
Oct 18, 2023
4a4c458 · Oct 18, 2023

History

History
44 lines (31 loc) · 1.01 KB

sort-my-animals.md

File metadata and controls

44 lines (31 loc) · 1.01 KB

Sort My Animals 6 Kyu

LINK TO THE KATA - LISTS SORTING FUNDAMENTALS

Description

Consider the following class:

var Animal = {
  name: 'Cat',
  numberOfLegs: 4,
}

Write a method that accepts a list of objects of type Animal, and returns a new list. The new list should be a copy of the original list, sorted first by the animal's number of legs, and then by its name.

If an empty list is passed in, it should return an empty list back.

Solution

const compareAnimals = (a, b) => {
  if (a.numberOfLegs < b.numberOfLegs) return -1
  if (a.numberOfLegs > b.numberOfLegs) return 1

  if (a.name < b.name) return -1
  if (a.name > b.name) return 1

  return 0
}

const sortAnimal = animals => {
  if (animals.length === 0) return []

  const animalsCopy = [...animals]

  return animalsCopy.sort(compareAnimals)
}