Skip to content
Advertisement

Javascript sort array of objects alphabetically AND put first objects with value

I’m trying to sort this data which contains various arrays of objects, the console.log of myData is something like:

[
  {
    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx'
  },
  {
    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'
  }
]
[
  {
    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'
  }
]

I’m trying to sort it alphabetically (based on value of name) and if the object has the parameter url , put it at the beginning.

So the output would be:

    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'

    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'

    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx'

what I tried is this, and many variations of it, but it doesn’t work:

var myData = props?.data

console.log(props?.data)

if(props.data){
  // those with url first, then alphabetically
  myData = props.data.sort(function(a, b){
    return b.url? 1 || (a.name < b.name) : -1;
  })
}

Advertisement

Answer

You can use !url as a number (0 or 1) and subtract them:

const arr = [{"name":"Cdb","image":"xxx","coll":"xxx"},{"name":"Bcd","image":"xxx","coll":"xxx","url":"myurl"},{"name":"Abc","image":"xxx","coll":"xxx"}]

arr.sort((a, b) => !a.url - !b.url || a.name.localeCompare(b.name));
  
console.log(arr)

This is saying that if exactly one of both has the url argument, that one should come first. Otherwise (if both have it, or neither have it) then the name is decisive.

This way, when multiple objects have the url argument, they will also be ordered among themselves by name.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement