Home > OS >  ordering sorting based multiple values
ordering sorting based multiple values

Time:03-11

I have a list of objects where the object has the below variables.

BO={Name: String, Position: Number, SortOrder: Number};

Here SortOrder is just a number starting with 1 and increments by one for subsequent objects in an ascending order. The name and position values are provided and sort order needs to be populated. These are the rules to sort the list:

1.Sort the list based on the value of position
2.If the two objects have same position value then we need to sort the objects based on the Name in an alphanumeric order

I can use simple sorting based on the value of position by using a loop and using the below logic, but I need to be able to sort based on Name if the two positions have the same value.

for(i=0;i<Arr.length;i  )
    {
      for(j=i 1;j<Arr.length;j  )
        {
          if(Arr[i].poition>Arr[j].position)
            {
              temp=Arr[j];
              Arr[j]=Arr[i];
              Arr[i]=temp;
        }
      }
    }

let me know how this can be achieved
e.g.1
given :
[{Name:A,Position:2}
,{Name:B,Position:1},
{Name:C,Position:3}
]

Out put:
[{Name:B,Position:1,SortOrder:1},
{Name:A,Position:2,SortOrder:2},
{Name:C,Position:3,SortOrder:3}]

e.g.2
given
[ {Name:Ab,Position:2},
{Name:A,Position:2},
{Name:HI,Position:4},
{Name:C,Position:3}
]
Out put:
[{Name:A,Position:2,SortOrder:1}
, {Name:Ab,Position:2,SortOrder:2}
, {Name:C,Position:3,SortOrder:3},
{Name:HI,Position:4,SortOrder:4}]

I am thinking of using a for loop and javascript to implement this. Thank You.

CodePudding user response:

You could sort and map.

const
    data = [{ Name: 'Ab', Position: 2 }, { Name: 'A', Position: 2 }, { Name: 'HI', Position: 4 }, { Name: 'C', Position: 3 }],
    result = data
        .sort((a, b) => a.Position - b.Position || a.Name.localeCompare(b.Name))
        .map((o, i) => ({ ...o, SortOrder: i   1 }));

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

CodePudding user response:

You can sort based on Position and in case of same position sort alphabetically using string#localeCompare()

const sorter = (arr) => arr.sort((a,b) => a.Position - b.Position || a.Name.localeCompare(b.Name));

const arr1 = [{ Name: 'A', Position: 2 }, { Name: 'B', Position: 1 }, { Name: 'C', Position: 3 }];
const arr2 = [ {Name:'Ab',Position:2}, {Name:'A',Position:2}, {Name:'HI',Position:4}, {Name:'C',Position:3} ];

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

  • Related