0

In js I have an array like this:

const arrayToSort = [{
    priority: 1,
    group: "a",
    id: "promo1"
  },
  {
    priority: 3,
    group: "a",
    id: "promo1"
  },
  {
    priority: 2,
    group: "a",
    id: "promo1"
  },
  {
    priority: 1,
    group: "b",
    id: "promo2"
  },
  {
    priority: 2,
    group: "e",
    id: "promo3"
  },
  {
    priority: 2,
    group: "c",
    id: "promo4"
  },
  {
    priority: 1,
    group: "f",
    id: "promo5"
  },
  {
    priority: 3,
    group: "d",
    id: "promo6"
  },
  {
    priority: 1,
    group: "g",
    id: "promo7"
  }
]

I need to sort that array first alphabetically by group field and then numerically by priority.

arrayToSort.sort((v1, v2) => {
    return (v1.group) > (v2.group) ? 1 : -1
});

Sorting by group works, but I did not find a solution to add priority sorting

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Bartek
  • 127
  • 6

1 Answers1

0

const data = [{"priority":1,"group":"a","id":"promo1"},{"priority":3,"group":"a","id":"promo1"},{"priority":2,"group":"a","id":"promo1"},{"priority":1,"group":"b","id":"promo2"},{"priority":2,"group":"e","id":"promo3"},{"priority":2,"group":"c","id":"promo4"},{"priority":1,"group":"f","id":"promo5"},{"priority":3,"group":"d","id":"promo6"},{"priority":1,"group":"g","id":"promo7"}]

const sortLexically =   p=>(a,b)=>a[p].localeCompare(b[p]);
const sortNumerically = p=>(a,b)=>a[p]-b[p];
const sortBy=sorts=>(a,b)=>sorts.reduce((r,s)=>r||s(a,b),0)

data.sort(sortBy([sortLexically('group'), sortNumerically('priority')]))

console.log(data)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • 2
    flag as duplicate (this is identical to the closing duplicate, but lacks any explanation and implements unnecessary abstraction to answer the question) – pilchard Nov 24 '22 at 15:17
  • Actually it is not working properly, output is not sorted by priority properly – Bartek Nov 24 '22 at 15:26
  • @Bartek there was a typo, i just fixed it – Andrew Parks Nov 24 '22 at 15:30
  • Could you look one more time? I do not know why by priority soting is still not working properly – Bartek Nov 24 '22 at 15:34
  • `[ { priority: 1, group: 'a', id: 'promo1' }, { priority: 3, group: 'a', id: 'promo1' }, { priority: 2, group: 'a', id: 'promo1' }, { priority: 1, group: 'b', id: 'promo2' }, { priority: 2, group: 'c', id: 'promo4' }, { priority: 3, group: 'd', id: 'promo6' }, { priority: 2, group: 'e', id: 'promo3' }, { priority: 1, group: 'f', id: 'promo5' }, { priority: 1, group: 'g', id: 'promo7' } ]` – Bartek Nov 24 '22 at 15:36
  • @Bartek sorry, totally screwed that up. Should be fixed now – Andrew Parks Nov 24 '22 at 15:52
  • @Bartek Since this question is closed, I've posted this solution here: https://stackoverflow.com/a/74563527/5898421 - an upvote there would be appreciated if it helps you solve your problem – Andrew Parks Nov 24 '22 at 16:13
  • Thank you @AndrewParks, works fine, vote added – Bartek Nov 25 '22 at 17:47