1

I'm trying to sort a list of Objects in ascending order. But there are cases when the sort value is null and in that case, the value should be sorted alphabetically.

I tried to create the following code:

let items = [
  {
   name: 'Foo',
   Km: null
  },
  {
   name: 'Bar',
   Km: 4
  },
  {
   name: 'BarFoo',
   Km: null
  },
  {
   name: 'FooBar',
   Km: 1
  },
]

function sortNullValues(values) {

    values.sort(function (a, b) {
    if(a.Km === null) return 1
    if(b.Km === null) return -1
    if (a.Km < b.Km) return 1
        if (a.Km < b.Km) return -1
    if (a.name > b.name) return -1
        if (a.name < b.name) return 1
  })

  return values
}

console.log(sortNullValues(items))

But the null valued objects are not sorting alphabetically. https://jsfiddle.net/am7n61ou/56/

Current Output:

[
  {
   name: 'Bar',
   Km: 4
  },
  {
   name: 'FooBar',
   Km: 1
  },
  {
   name: 'Foo',
   Km: null
  },
  {
   name: 'BarFoo',
   Km: null
  }
]

Desired Output:

[
  {
   name: 'FooBar',
   Km: 1
  },
  {
   name: 'Bar',
   Km: 4
  },
  {
   name: 'BarFoo',
   Km: null
  },
  {
   name: 'Foo',
   Km: null
  }
]
1
  • 1
    if(a.Km === null) return 1 will catch the case when both a and b are null: jsfiddle.net/khrismuc/vyqc1mwf Commented Apr 9, 2019 at 18:21

2 Answers 2

3

You could first sort the null values to bottom, sort by Km (null - nullis zero) or by string.

var array = [{ name: 'Foo', Km: null }, { name: 'Bar', Km: 4 }, { name: 'BarFoo', Km: null }, { name: 'FooBar',  Km: 1 }];

array.sort((a, b) => 
    (a.Km === null) - (b.Km === null) ||
    a.Km - b.Km ||
    a.name.localeCompare(b.name)
);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

2 Comments

Works great. What's happening here: a.name.localeCompare(b.name) ?
String#localeCompare is a method for comparing strings.
0

You function always returns -1 even if both values are null. I've fixed your code. You should check for null values and return different sorting.

Corrected code:

  values.sort(function (a, b) {
    if (a.Km === null && b.Km === null) {
      if (a.name > b.name) return 1
      if (a.name < b.name) return -1
        }
    if(a.Km === null) return 1
    if(b.Km === null) return -1
    if (a.Km < b.Km) return 1
        if (a.Km < b.Km) return -1
  })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.