Home > Back-end >  Move elements to top in array of objects
Move elements to top in array of objects

Time:10-29

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, 
.....}

)

CodePudding user response:

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)

  • Related