0

I want to sort Below array based on name and is_closed.

this.rawDataListDup = [
    {id: 1, name: 'john','is_closed':true},
    {id: 2, name: 'james','is_closed':true},
    {id: 3, name: 'jane','is_closed':false},
    {id: 4, name: 'alex','is_closed':false},
    {id: 5, name: 'david','is_closed':true},
];

As of now i can only sort using any one of the attribute using below code.

let colName = 'name'
this.rawDataListDup.sort((b, a) => a[colName] < b[colName] ? 1 : a[colName] > b[colName] ? -1 : 0)

I want array objects with is_closed = false on top of array and also it should be in Alphabetical order. like this

this.rawDataListDup = [
    {id: 4, name: 'alex','is_closed':false},
    {id: 3, name: 'jane','is_closed':false},
    {id: 5, name: 'david','is_closed':true},
    {id: 2, name: 'james','is_closed':true},
    {id: 1, name: 'john','is_closed':true},
];

how to do this?

BLU
  • 61
  • 8
  • `rawDataListDup.sort((a,b)=>(a.is_closed-b.is_closed) || a.name.localeCompare(b.name))` – gorak Feb 24 '21 at 11:49
  • 4
    Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – Sourabh Somani Feb 24 '21 at 11:56

3 Answers3

4

You can do this with sort with multiple conditions inside sort:

const rawDataListDup = [
    {id: 1, name: 'john','is_closed':true},
    {id: 2, name: 'james','is_closed':true},
    {id: 3, name: 'jane','is_closed':false},
    {id: 4, name: 'alex','is_closed':false},
    {id: 5, name: 'david','is_closed':true},
];

const sortedList = rawDataListDup.sort((a,b)=>(a.is_closed-b.is_closed) || a.name.localeCompare(b.name));

console.log(sortedList);
gorak
  • 5,233
  • 1
  • 7
  • 19
0

It just write simple code.

const rawDataListDup = [
    {id: 1, name: 'john','is_closed':true},
    {id: 2, name: 'james','is_closed':true},
    {id: 3, name: 'jane','is_closed':false},
    {id: 4, name: 'alex','is_closed':false},
    {id: 5, name: 'david','is_closed':true},
];

rawDataListDup.sort(function(a, b) {
  return a.is_closed - b.is_closed  ||  a.name - b.name;
});
//OR 
    var obj = rawDataListDup.sort((a, b) => a.is_closed - b.is_closed || a.name - b.name);
Inam Abbas
  • 468
  • 3
  • 8
0

You could also use lodash (sortBy).

Example: _.sortBy(rawDataListDup, ['is_closed', 'name']);

Daniela Donna
  • 250
  • 4
  • 12