Home > Blockchain >  Sort object keys by custom logic
Sort object keys by custom logic

Time:08-31

I have an object in javascript that looks like this:

const inventory = {
   fall: { 'Category 1': [], 'Category 2': [] },
   spring: { 'Category 1': [], 'Category 3': [] },
   winter: { 'Category 3': [], 'Category 4': [] },
   summer: { 'Category 4': [], 'Category 5': [] }
}

How can I sort by keys so that those are ordered as follows:

  1. spring
  2. summer
  3. fall
  4. winter

CodePudding user response:

Destructuring assignment

const { spring, summer, fall, winter } = {
  fall: { 'Category 1': [], 'Category 2': [] },
  spring: { 'Category 1': [], 'Category 3': [] },
  winter: { 'Category 3': [], 'Category 4': [] },
  summer: { 'Category 4': [], 'Category 5': [] }
};

const inventory = { spring, summer, fall, winter }

CodePudding user response:

You just need to create new object with this sorting.

const inventory = {
   fall: { 'Category 1': [], 'Category 2': [] },
   spring: { 'Category 1': [], 'Category 3': [] },
   winter: { 'Category 3': [], 'Category 4': [] },
   summer: { 'Category 4': [], 'Category 5': [] }
}

const { fall, spring, winter, summer } = inventory;

const sortingInventory = {
  spring,
  summer,
  fall,
  winter,
}


console.log(sortingInventory)

FOR SORTING ALGHPITICALLY.

const inventory = {
   fall: { 'Category 1': [], 'Category 2': [] },
   spring: { 'Category 1': [], 'Category 3': [] },
   winter: { 'Category 3': [], 'Category 4': [] },
   summer: { 'Category 4': [], 'Category 5': [] }
}

const result = Object.fromEntries(Object.entries(inventory).sort((a, b) => {
  return a[0].localeCompare(b[0])
}))

console.log(result)

  • Related