1

I have an array of teachers, where each one have a property user with image property, that can contain a string or null value. How can i order the array, considering the user.image property?

Here is an example of structure.

const teachers = [
    {
        id: 1,
        user: {
            id: 10,
            image: "image.jgp"
        }
    },
    {
        id: 3,
        user: {
            id: 30,
            image: null
        }
    },
    {
        id: 2,
        user: {
            id: 20,
            image: "image.jgp"
        }
    },
    {
        id: 4,
        user: {
            id: 40,
            image: null
        }
    },
]
Spectric
  • 30,714
  • 6
  • 20
  • 43
Facundo Serrano
  • 43
  • 2
  • 12
  • 1
    What should their order be? There's only two values – evolutionxbox Sep 03 '21 at 15:16
  • 3
    Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – iunfixit Sep 03 '21 at 15:18
  • The order should be, first all objects which `user.image` is a string, and, all which `user.image` is null, in the final. The array is just a example and the structure just have the basic to explain the problem. – Facundo Serrano Sep 03 '21 at 15:19
  • It's a matter of writing a sort function, which compares two elements from your array. In your case, it would be something like `(a, b) => a.user.image.localeCompare(b.user.image)`. I wrote about comparing objects: https://www.freecodecamp.org/news/supercharged-sorts-in-javascript/ – Snowmonkey Sep 03 '21 at 15:21
  • It doesn't, because i just mind if are a value, not the unicode o value – Facundo Serrano Sep 03 '21 at 15:22
  • @Snowmonkey `localeCompare` doesn’t exist on `null`. – Sebastian Simon Sep 03 '21 at 15:23
  • Could get funky: `(a,b)=>Number(Boolean(a.user.image))-Number(Boolean(b.user.image))` a null would be zero, any string would be one. – Snowmonkey Sep 03 '21 at 16:05

1 Answers1

2

You can use Array.sort and check whether the image property is null:

const teachers=[{id:1,user:{id:10,image:"image.jgp"}},{id:3,user:{id:30,image:null}},{id:2,user:{id:20,image:"image.jgp"}},{id:4,user:{id:40,image:null}}];

const sorted = teachers.sort((a, b) => b.user.image === null ? -1 : 1)

console.log(sorted)
Spectric
  • 30,714
  • 6
  • 20
  • 43