0

I have an object like this:

var obj = [
    { name: "name1", type: 4 },
    { name: "name6", type: 2 },
    { name: "name2", type: 5 }, 
    { name: "name3", type: 1 }, 
    { name: "name5", type: 2 }, 
    { name: "name4", type: 3 }
]

I want to return a sorted array, so that at the top of the array there are objects with type 2 or 3, sorted further by the name field:

var obj = [
    { name: "name4", type: 3 }
    { name: "name5", type: 2 },
    { name: "name6", type: 2 },
    { name: "name1", type: 4 },
    { name: "name2", type: 5 }, 
    { name: "name3", type: 1 } 
]

How can I implement this?

p.s. I would also like to see a variant if type is enum (e.g.,

export enum Types {
Type0 = 0, 
Type1 = 1, 
.....}

)

1 Answer 1

2

You need to sort first on whether the type is one of 2 or 3 (you can do this by checking whether the type value exists in an array [2, 3]; we sort that as a descending sort since we want true results first), and then on the name:

var obj = [
    { name: "name1", type: 4 },
    { name: "name6", type: 2 },
    { name: "name2", type: 5 }, 
    { name: "name3", type: 1 }, 
    { name: "name5", type: 2 }, 
    { name: "name4", type: 3 }
]

const firstTypes = [2, 3]

obj.sort((a, b) =>
  firstTypes.includes(b.type) - firstTypes.includes(a.type) ||
  a.name.localeCompare(b.name)
)

console.log(obj)

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

2 Comments

ty! small question. If type is an enum (export enum Types {Type0 = 0, Type 1 = 1, .....}). Do I have to use Object.values somehow when sorting?
@Stranger it should just work as is: typescriptlang.org/play?#code/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.