user2004
user2004

Reputation: 1973

sort array by property without using the first object

I have an array of objects and I want to sort them by the object ids. I tried using options.sort((a, b) => a.id.localeCompare(b.id)); but did not worked as expected because it is sorting even the 'all' object and I don't want this (the object with id='all' should be first in my array, after that should be the objects in ascending order). Below you can see the input and the output of my code

Input:

 var items = 
           [{ 'Name':'All', 'id': 'all'
            { 'Name':'item1', 'id': '003' }
            { 'Name':'item2', 'id': '001' }
            { 'Name':'item3', 'id': '002' }];

Output:

  var items = 
           [{ 'Name':'item2', 'id': '001' }
            { 'Name':'item3', 'id': '002' }
            { 'Name':'item1', 'id': '003' }
            { 'Name':'All', 'id': 'all'}];

Upvotes: 1

Views: 50

Answers (2)

anonymous
anonymous

Reputation: 1691

It should work

var items = 
           [{ 'Name':'All', 'id': 'all' },
            { 'Name':'item1', 'id': '003' },
            { 'Name':'item2', 'id': '001' },
            { 'Name':'item3', 'id': '002' }];
            
   items.sort((a, b) => ((typeof b.id === "number") - (typeof a.id === "number")) || (a.id > b.id ? 1 : -1));

// items.sort((a, b) => (((typeof b.id === "number") as any) - ((typeof a.id === "number") as any)) || (a.id > b.id ? 1 : -1) );

  console.log(items)

Upvotes: 0

Anil Kumar
Anil Kumar

Reputation: 65

 function compare(key, order = 'desc') {
  return (a, b) => {
    if (a[key] > b[key])
      return order === 'desc' ? -1 : 1;
    if (a[key] < b[key])
      return order === 'desc' ? 1 : -1;
    return 0;
  };
 }


const data = [
      { 'Name':'All', 'id': 'all'},
      { 'Name':'item3', 'id': '003' },
      { 'Name':'item1', 'id': '001' },
      { 'Name':'item2', 'id': '002' }
 ];
 
 const sortedData = data.sort(compare('Name', 'asce'));
 console.log('sorted: ', sortedData);

Upvotes: 1

Related Questions