Home > Back-end >  i want to sort objects in descending order in JavaScript output should be like the given image
i want to sort objects in descending order in JavaScript output should be like the given image

Time:10-17

{
  "count": 1000,
  "products": {
    "6834": {
      "subcategory": "mobile",
      "title": "Micromax Canvas Spark",
      "price": "4999",
      "popularity": "51936"
    },
    "5530": {
      "subcategory": "mobile",
      "title": "Samsung Galaxy Grand Max",
      "price": "12950",
      "popularity": "48876"
    },
    "4340": {
      "subcategory": "mobile",
      "title": "Apple iPhone 6",
      "price": "40999",
      "popularity": "46198"
    },
    "4804": {
      "subcategory": "mobile",
      "title": "Samsung Galaxy Grand Prime",
      "price": "9286",
      "popularity": "45775"
    },
    "5266": {
      "subcategory": "mobile",
      "title": "Micromax Canvas Nitro A311",
      "price": "7769",
      "popularity": "44273"
    },
    "5629": {
      "subcategory": "mobile",
      "title": "Samsung Galaxy E7",
      "price": "15763",
      "popularity": "40345"
    }
}

enter image description here

CodePudding user response:

you can do something like this

const data = { "count": 1000, "products": { "6834": { "subcategory": "mobile", "title": "Micromax Canvas Spark", "price": "4999", "popularity": "51936" }, "5530": { "subcategory": "mobile", "title": "Samsung Galaxy Grand Max", "price": "12950", "popularity": "48876" }, "4340": { "subcategory": "mobile", "title": "Apple iPhone 6", "price": "40999", "popularity": "46198" }, "4804": { "subcategory": "mobile", "title": "Samsung Galaxy Grand Prime", "price": "9286", "popularity": "45775" }, "5266": { "subcategory": "mobile", "title": "Micromax Canvas Nitro A311", "price": "7769", "popularity": "44273" }, "5629": { "subcategory": "mobile", "title": "Samsung Galaxy E7", "price": "15763", "popularity": "40345" }}}


const orderedProducts = Object.values(data.products).sort((a, b) => Number(b.popularity) - Number(a.popularity))


console.log(orderedProducts)

  • Related