0

So I have an array like the one in the code below, and I would want to sort it on height. So that the shortest person will log when I do console.log(array[0]);

I have no idea how to do so

let array = [
    {
        name: "John",
        gender: "male",
        height_meters: 1.8
    },
    {
        name: "Cathrine",
        gender: "female",
        height_meters: 1.7
    }
]
  • 3
    If you read [the documentation on array sorting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), you'll see explanations and examples. – nem035 Dec 27 '18 at 22:51
  • 1
    `array.sort(person => person.height_meters)`. The argument to the sort method lets you specify how elements should be compared (identity by default) – wbadart Dec 27 '18 at 22:52
  • 1
    @wbadart, that is not right. you need both arguments and the delta of the property. – Nina Scholz Dec 27 '18 at 22:54

3 Answers3

2

We seperate out the sort here, it allows us to have clarity to our code, but also makes it easy to swap out or re-use. Sort is looking for us to return one of three values in order for it to sort elements. Less than zero 0 and Greater than zero. Most documentation will show this as a rigid -1, 0, 1. But any positive and negative can be substituted for the -1 and +1 which gives us the ability to be so concise when sorting numbers.

let array = [
    {
        name: "John",
        gender: "male",
        height_meters: 1.8
    },
    {
        name: "Cathrine",
        gender: "female",
        height_meters: 1.7
    },
    {
        name: "Cathrine",
        gender: "female",
        height_meters: 1.3
    },
    {
        name: "Cathrine",
        gender: "female",
        height_meters: 1.95
    },
    {
        name: "Cathrine",
        gender: "female",
        height_meters: 2.7
    }
]

const sortBy = (itemA, itemB) => itemA.height_meters - itemB.height_meters;

console.log(array.sort(sortBy));
Bibberty
  • 4,670
  • 2
  • 8
  • 23
1

Native way

arr.sort((a, b) => a.height_meters - b.height_meters);

With Lodash library

_.orderBy(arr, ['height_meters'], ['asc']);
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
0

Use array.sort():

array.sort((a,b)=>{
    return a.height_meters-b.height_meters
})

I hope this will help!

FZs
  • 16,581
  • 13
  • 41
  • 50